Finding common value among sub-arrays in a multidimensional array
This works for me:
function multi_intersect($arr) {
$return = array();
foreach ($arr as $a) {
foreach ($arr as $b) {
if ($a === $b) continue;
$return = array_merge($return, array_intersect($a, $b));
}
}
return array_unique($return);
}
Should get you:
Array
(
[0] => 58
)
The above will work if you have a common number in at least two of the sub-arrays.
After your edit:
You can simply use call_user_func_array
on array_intersect
, if you want to find numbers that are contained in all sub-arrays:
$intersect = call_user_func_array('array_intersect', $arr);
Find Common most values in multidimensional array in PHP
You might use a foreach
and use the array values as the key and increment each times it matches.
At the end sort the keys using ksort and return the keys using array_keys :
$arrays = [
['000', '001', '002', '003'],
['000', '001', '002'],
['000', '001'],
['000', '001', '002', '003'],
['000', '001', '002'],
['000', '001'],
];
$result = [];
foreach ($arrays as $array) {
foreach ($array as $a) {
if (!array_key_exists($a, $result)) {
$result[$a] = 1;
continue;
}
$result[$a] += 1;
}
}
ksort($result);
print_r(array_keys($result));
Demo
Ouput
Array
(
[0] => 000
[1] => 001
[2] => 002
[3] => 003
)
Php - How to find common elements from multidimensional array?
For PHP 5.6 and above, you can directly use array_intersect()
with the ...
token (also called splat operator in other languages):
$city = array(
array(1, 2, 3, 4),
array(1, 2, 3, 4, 5),
array(2, 3, 4, 5),
);
$inter = array_intersect(...$city);
Performance-wise this is much faster than call_user_func_array()
PHP - Compare multidimensional sub-arrays to each other and merge on similarity threshold
I'll give it a go!
I use preg_grep to find items that are the same in the other subarrays. Then I use count to see how many matching keywords there is.
And that is where the threshold is. Currently I set it to 2
, that means two matching keywords is a match.
//flatten array to make it simpler
$new =[];
foreach($array as $subarr){
$new = array_merge($new, $subarr);
}
$threshold = 2;
$merged=[];
foreach($new as $key => $story){
// create regex pattern to find similar items
$words = "/" . implode("|", $story["keywords"]) . "/i";
foreach($new as $key2 => $story2){
// only loop new items and items that has not been merged already
if($key != $key2 && $key2 > $key && !in_array($key2, $merged)){
// If the count of words from preg_grep is above threshold it's mergable
if(count(preg_grep($words, $story2["keywords"])) > $threshold){
// debug
//echo $key . " " . $key2 . "\n";
//echo $story["header"] . " = " . $story2["header"] ."\n\n";
// if the item does not exist create it first to remove notices
if(!isset($res[$key])) $res[$key] = ["header" => [], "keywords" =>[]];
// add headers
$res[$key]["header"][] = $story["header"];
$res[$key]["header"][] = $story2["header"];
// only keep unique
$res[$key]["header"] = array_unique($res[$key]["header"]);
// add keywords and remove duplicates
$res[$key]["keywords"] = array_merge($res[$key]["keywords"], $story["keywords"], $story2["keywords"]);
$res[$key]["keywords"] = array_unique($res[$key]["keywords"]);
// add key2 to merged so that we don't merge this again.
$merged[] = $key2;
}
}
}
}
var_dump($res);
https://3v4l.org/6cKRq
Output is as your "wanted" in question.
Access of first sub-array from a multi-dimensional array
If you look closely, you will see that F_matrix[0]
consists of 8 sub arrays (1-d arrays). Hence you get len(F_matrix[0])
as 8. Furthermore, each of these 8 subarrays contains 8 elements so you have total 8x8 = 64 elements.
Now if you do
len(F_matrix[0][0])
you will see that it will also result in 8. Since you have 8 subarrays, F_matrix[0]
will have indices running from 0 to 7. Specifically, each of
which will have a length fo 8 as
print (len(F_matrix[0][0])) # 8
print (len(F_matrix[0][1])) # 8
print (len(F_matrix[0][2])) # 8
.
.
.
print (len(F_matrix[0][7])) # 8
EDIT
To get the total number of elements in your general multidimensional array, you first need to flatten all the dimensions to 1-d and then compute the length. So for your example, to get the length (64) you can do
print (len(F_matrix.flatten()))
len(F_matrix[0])
represents the length (size) of the first dimension. Since you have a 3d array (1,8,8)
, length of F_matrix[0]
means how many further elements (can be array or list etc.) contains. These elements can in themselves be multidimensional.
Filter multidimensional array by equal values in sub array (PHP)
You can create two arrays with the help of filtering by necessary values. You can use array_filter function to it, but you should find a necessary value in each element that passed to array_filter function.
For example, finding 'req' value
$req = array_filter($my_array, function ($v) {
return in_array('req', $v);
});
For example, finding 'opt' value
$opt = array_filter($my_array, function ($v) {
return in_array('opt', $v);
});
I used in_array function to finding values because each element is an array that has different quantity of elements
How to get common values from 4 multidimensional arrays using array_intersect
If subarray contain one element always you could chage that value using array_map and current function.
$arr=array(array(8159),array(8140),array(8134),array( 8168),array(8178),array( 8182),array( 8183));
$arr1=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr2=array(array(566),array(265),array(8134),array(655),array(8166),array(665),array( 8168),array(656),array( 989),array( 989));
$arr3=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr = array_map('current', $arr); // getting first value of subarray
$arr1 = array_map('current', $arr1);
$arr2 = array_map('current', $arr2);
$arr3 = array_map('current', $arr3);
print_r($arr3);
// Array
// (
// [0] => 8159
// [1] => 8140
// [2] => 8134
// [3] => 8165
// [4] => 8166
// [5] => 8167
// [6] => 8168
// )
$res= array_intersect($arr,$arr1,$arr2,$arr3);
print_r($res);
// Array
// (
// [2] => 8134
// [3] => 8168
// )
Using array_intersect on a multi-dimensional array
Use array_uintersect()
to use a custom comparison function, like this:
$arr1 = array(
array('name' => 'asdfjkl;', 'value' => 'foo'),
array('name' => 'qwerty', 'value' => 'bar'),
array('name' => 'uiop', 'value' => 'baz'),
);
$arr2 = array(
array('name' => 'zxcv', 'value' => 'stuff'),
array('name' => 'asdfjkl;', 'value' => 'foo'),
array('name' => '12345', 'value' => 'junk'),
array('name' => 'uiop', 'value' => 'baz'),
);
$intersect = array_uintersect($arr1, $arr2, 'compareDeepValue');
print_r($intersect);
function compareDeepValue($val1, $val2)
{
return strcmp($val1['value'], $val2['value']);
}
which yields, as you would hope:
Array
(
[0] => Array
(
[name] => asdfjkl;
[value] => foo
)
[2] => Array
(
[name] => uiop
[value] => baz
)
)
Related Topics
Error Executing "Putobject" on Aws, Upload Fails
How to Get the List of Available Locales in PHP
How to Convert an Integer to an Array in PHP
How to Check If File Is Ascii or Binary in PHP
Codeigniter Redirect -- the Uri You Submitted Has Disallowed Characters
Mysql: Group by Two Columns and Sum
Comparing Floats - Same Number, But Does Not Equal
JavaScript Cookies VS PHP Cookies
Dates Not Casting After Upgrading to Laravel 7
How to Prevent Self Closing Tag in PHP Simplexml
How to 'JSON_Encode()' Keys from PHP Array
Call to Undefined Function Odbc_Connect() PHP 7
Client Side VS Server Side Basics