Minh Loc Minh Loc - 7 months ago 95
PHP Question

Compare multidimensional arrays with array_diff

I have 2 arrays then i want to filter them by email key. Like this

Array1

array (size=5)
0 =>
array (size=3)
'name' => string 'Client 1' (length=8)
'email' => string 'client1@gmail.com' (length=17)
1 =>
array (size=3)
'name' => string 'Client 2' (length=8)
'email' => string 'client2@gmail.com' (length=17)


Array2

array (size=3)
0 =>
array (size=4)
'name' => string 'Client 3' (length=8)
'email' => string 'client2@gmail.com' (length=17)
'role_id' => float 3
1 =>
array (size=4)
'name' => string 'Client 6' (length=8)
'email' => string 'client6@gmail.com' (length=17)
'role_id' => float 2
2 =>
array (size=4)
'name' => string 'Client 7' (length=8)
'email' => string 'client7@gmail.com' (length=17)
'role_id' => float 3


I want to filter out the similar email items. How can result return like below:

array (size=2)
0 =>
array (size=4)
'name' => string 'Client 6' (length=8)
'email' => string 'client6@gmail.com' (length=17)
'role_id' => float 2
1 =>
array (size=4)
'name' => string 'Client 7' (length=8)
'email' => string 'client7@gmail.com' (length=17)
'role_id' => float 3

Answer

You could use array_udiff.

If will filter the first array, by comparing its elements to the elements of other arrays passed to array_udiff using the given callback. When the callback returns 0 for a pair, that element is removed from the result.

$result = array_udiff($arr2, $arr1, function ($a, $b) {
    return strcmp($a['email'], $b['email']);
});