Finding common value among sub-arrays in a multidimensional array

前端 未结 2 1763
醉梦人生
醉梦人生 2020-12-03 16:44

I have the following array:

Array
(
    [0] => Array
        (
            [0] => 87
            [1] => 58
            [2] => 85
            [3]          


        
相关标签:
2条回答
  • 2020-12-03 16:52

    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 讨论(0)
  • 2020-12-03 17:11

    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);
    
    0 讨论(0)
提交回复
热议问题