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
)
)
The array_diff_assoc() function compares the keys and values of two (or more) arrays, and returns the differences. This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
To compare array's structure, You should use identity operator. The only difference(s) between this and my answer is that instead of using == for the elements in the array, it will use === , and with === it checks the order of key value pairs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With