Search code examples
phparraysmultidimensional-arrayfilterarray-difference

Filter a 2d associative array by the keys of another 2d associative array


I have two multidimensional arrays and I want the difference. For eg. I have taken two-dimensional two arrays below

$array1 = Array (
       [a1] => Array  (
          [a_name] => aaaaa
          [a_value] => aaa
     )

       [b1] => Array (
          [b_name] => bbbbb
          [b_value] => bbb
   )
       [c1] => Array (
          [c_name] => ccccc
          [c_value] => ccc
   )

)

$array2 = Array (
 [b1] => Array (
       [b_name]=> zzzzz
     )
)

Now I want the key difference of these two arrays. I have tried array_diff_key() but it doesnot work for multidimensional.

array_diff_key($array1, $array2)

I want the output as following

//output
$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
 )

   [b1] => Array (          
      [b_value] => bbb
)
   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
)

)

If you think my question is genuine please accept it and answer. Thank you.

EDIT

Now if the second array is

$array2 = Array( [b1] => zzzzz)

The result should be

$array1 = Array (
   [a1] => Array  (
      [a_name] => aaaaa
      [a_value] => aaa
    )     

   [c1] => Array (
      [c_name] => ccccc
      [c_value] => ccc
     )

)

Solution

  • Please check if I understand you correctly then this code snippet can help to you solve your problem. I have tested it for your specified problem only. if there are other testcases for which you want to run this, you can tell me to adjust the code.

    $a1 = array(
        'a1' => array('a_name' => 'aaa', 'a_value' => 'aaaaa'),
        'b1' => array('b_name' => 'bbb', 'b_value' => 'bbbbbb'),
        'c1' => array('c_name' => 'ccc', 'c_value' => 'cccccc')
    );
    
    $a2 = array(
        'b1' => array('b_name' => 'zzzzz'),
    );
    
    $result = check_diff_multi($a1, $a2);
    print '<pre>';
    print_r($result);
    print '</pre>';
    
    
    function check_diff_multi($array1, $array2){
        $result = array();
        foreach($array1 as $key => $val) {
             if(isset($array2[$key])){
               if(is_array($val) && $array2[$key]){
                   $result[$key] = check_diff_multi($val, $array2[$key]);
               }
           } else {
               $result[$key] = $val;
           }
        }
    
        return $result;
    }
    

    EDIT: added tweak to code.