array_diff() with multidimensional arrays
Using array_diff()
, I can compare and remove similar items, but what if I have the following arrays?
Array1
Array
(
[0] => Array
(
[ITEM] => 1
)
[1] => Array
(
[ITEM] => 2
)
[2] => Array
(
[ITEM] => 3
)
)
Array2
Array
(
[0] => Array
(
[ITEM] => 2
)
[1] => Array
(
[ITEM] => 3
)
[2] => Array
(
[ITEM] => 1
)
[3] => Array
(
[ITEM] => 4
)
)
I want to filter out the similar items; result should return 4. How can I rearrange my array so that I can use array_diff()
?
You can define a custom comparison function using array_udiff()
.
function udiffCompare($a, $b)
{
return $a['ITEM'] - $b['ITEM'];
}
$arrdiff = array_udiff($arr2, $arr1, 'udiffCompare');
print_r($arrdiff);
Output:
Array
(
[3] => Array
(
[ITEM] => 4
)
)
This uses and preserves the arrays' existing structure, which I assume you want.
I would probably iterate through the original arrays and make them 1-dimensional... something like
foreach($array1 as $aV){
$aTmp1[] = $aV['ITEM'];
}
foreach($array2 as $aV){
$aTmp2[] = $aV['ITEM'];
}
$new_array = array_diff($aTmp1,$aTmp2);
Another fun approach with a json_encode
trick (can be usefull if you need to "raw" compare some complex values in the first level array) :
// Compare all values by a json_encode
$diff = array_diff(array_map('json_encode', $array1), array_map('json_encode', $array2));
// Json decode the result
$diff = array_map('json_decode', $diff);