How can I check if the values are unique in an array based on the key value?
Below is the output of the array. I want to remove duplicate values based on the "id" key. If you check below, the 2nd & 3rd array are same except for the "role" value. Because of this, array_unique is not working on this array.
[
[
'id' => '1521422',
'name' => 'David Alvarado',
'role' => 'associate producer ',
],
[
'id' => '0098210',
'name' => 'Cristian Bostanescu',
'role' => 'line producer: Romania (as Cristi Bostanescu)',
],
[
'id' => '1266015',
'name' => 'Bruno Hoefler',
'role' => 'co-producer ',
],
[
'id' => '1266015',
'name' => 'Bruno Hoefler',
'role' => 'executive producer ',
],
[
'id' => '1672379',
'name' => 'Alwyn Kushner',
'role' => 'associate producer ',
],
]
Try this one:
<?php
$array = array(
array('id' => 1, 'text' => 'a'),
array('id' => 2, 'text' => 'b'),
array('id' => 1, 'text' => 'c'),
array('id' => 3, 'text' => 'd')
);
$array = array_filter($array, function ($item) {
static $found = array();
if (isset($found[$item['id']])) return false;
$found[$item['id']] = true;
return true;
});
var_dump($array);
This works as of PHP 5.3 (because of the closure and static statement).
cf. http://php.net/manual/en/function.array-filter.php for more information. I tested the statement within loops, it works there as well.