php arrays finding the elements present in all sub-arrays
I have a php multidimensional array (2 levels) with some values and I want to identify what values are present in all arrays.
Array
(
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 1
[1] => 2
)
[3] => Array
(
[0] => 1
[1] => 3
)
)
....in our case value 1 is present in开发者_JAVA百科 all 2nd level arrays. Is there a way to identify that?
You can use array_intersect
to do an intersection of all arrays:
$intersection = $arr[0];
for ($i=1, $n=count($arr); $i<$n; ++$i) {
$intersection = array_intersect($intersection, $arr[$i]);
if (empty($intersection)) break;
}
Or a little shorter using call_user_func_array
:
$intersection = call_user_func_array('array_intersect', $arr);
精彩评论