开发者

Finding common value among sub-arrays in a multidimensional array

开发者 https://www.devze.com 2023-02-05 02:55 出处:网络
I have the following array: Array ( [0] => Array ( [0] => 87 [1] => 58 [2] => 85 [3] => 8开发者_JAVA技巧6

I have the following array:

Array
(
    [0] => Array
        (
            [0] => 87
            [1] => 58
            [2] => 85
            [3] => 8开发者_JAVA技巧6
        )

    [1] => Array
        (
            [0] => 58
            [1] => 84
        )

    [2] => Array
        (
            [0] => 58
        )

)

This array above is an example. The actual array is of variable size, but structured like this. Basically, I'd like to run array_intersect on each second level array and grab the value (number) that is common between them. In this case, it would be 58.

I'm not quite sure where to start on this. Any advice?


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);


If there is a mistake in your example and there should be 58 in the [0] element of 'root' array you should just run

$res = $arr[0]; foreach($arr as $elem) $res = array_intersect($res, $elem);

More general solution (nested arrays):

<?php
//$arr -> your multidimensional array
function array_intersect_recursive($arr) {
  $first = true;
  foreach($arr as $elem) {
    if(is_array($elem)) $elem = array_intersect_recursive($arr);
    if($first) { $first = false; $res = $elem; } 
    else $res =  array_intersect($res, $elem);
  } 

}

I haven't tested it, but I hope you get the idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消