I'm trying to find the difference between two multi-dimensional associative arrays. Specifically any elements in the first array that are no present or different in the second array only. Not the other way around. Hence, 'y'=>1 is not part of the result.
$arra = ['x'=>1, 'y'=>1, 'z'=>1, 'add'=>['a'=>1]];
$arrb = ['x'=>2, 'y'=>1, 'add'=>[]];
To get this result:
['x'=>1, 'z'=>1, 'add'=>['a'=>1]];
I can use array_diff_assoc($arra, $arrb)
if the arrays are 1D.
But is there something I can use to handle the inner array 'add'?
I can write my own function to recursively look through the array, but is there something simpler available?
Thanks.
EDIT: Using @abracadaver's answer, I tried
function sortAndSerialize($arr){
ksort($arr);
return serialize($arr);
}
array_map('unserialize', array_diff(array_map('sortAndSerialize', [$arra]), array_map('sortAndSerialize', [$arrb])));
But it returns the following
Array ( [0] => Array ( [add] => Array ( [a] => 1 ) [x] => 1 [y] => 1 [z] => 1 ) )
Note: I updated my original array so it has identical and different elements.
The question isn't a duplicate. The other question uses an array where each element is an array. In this case, the elements may be arrays or strings etc. The other solution doesn't work here.
EDIT2: AbraCadaver answer:
$result = array_filter($arra, function($v, $k) use($arrb) { return (!isset($arrb[$k]) || $arrb[$k] !== $v); }, ARRAY_FILTER_USE_BOTH);
works well for my original arrays which are associative.
It doesn't work if the arrays are indexed however. For example:
$arra = ['x'=>1, 'y'=>1, 'z'=>1, 'add'=>[3,5]];
$arrb = ['x'=>2, 'y'=>1, 'add'=>[3]];
This returns:
['x'=>1, 'z'=>1, 'add'=>[3,5]];
Instead of:
['x'=>1, 'z'=>1, 'add'=>[5]];
Basically anything inside a non-assc array is not compared and entire contents are returned, unless identical.
It would help to look into how to get it to work for both associative and non-associative arrays.