Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

multidimensional array difference php

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
     )

)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...