PHP: How to list the keys of two multidimensional arrays for which the values are different?

Viewed 52

How to list the keys of two multidimensional arrays for which the value ares different ?

Example of given array.

$array1 = [
  'a' => 'Barbapapa',
  'b' => 'Barbouille',
  'c' => [
    'foo' => 'Barbamama'
  ],
  'd' => 'Barbabelle'
];
$array2 =[
  'a' => 'Barbapapa',
  'b' => 'Barbotine',
  'c' => [
    'foo' => 'Barbamama',
    'bar' => 'Barbidur'
  ]
]

Returned array (any other format is fine):

['b', 'c.bar', 'd']

So, I tried this (from this post):

function arrayRecursiveDiff($aArray1, $aArray2) {
  $aReturn = array();

  foreach ($aArray1 as $mKey => $mValue) {
    if (array_key_exists($mKey, $aArray2)) {
      if (is_array($mValue)) {
        $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
        if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
      } else {
        if ($mValue != $aArray2[$mKey]) {
          $aReturn[$mKey] = $mValue;
        }
      }
    } else {
      $aReturn[$mKey] = $mValue;
    }
  }
  return $aReturn;
}
>>> arrayRecursiveDiff($array1, $array2)
=> [
     "b" => "Barbouille",
     "d" => "Barbabelle",
   ]

But I'm not getting the missing c.bar.

1 Answers

Add these two functions

function array_merge_xor($a, $b) {
    $result = array_merge(array_diff($a, $b), array_diff($b, $a));
    return $result;
}

function array_flatten($array) {
    $return = array();
    foreach ($array as $key => $value) {
        if (is_array($value)){
            foreach($value as $subKey => $subVal){
                $valueNew[$key.'.'.$subKey] = $value[$subKey];
            }
            
            $return = array_merge($return, array_flatten($valueNew));
        } else {
            $return[$key] = $value;
        }
    }

    return $return;
}

And then call your arrays like this....

$x = array_merge_xor(array_flatten($array1), array_flatten($array2));

print_r($x);
Related