user2957386
user2957386

Reputation: 35

Remove duplicates in an array based on a specific field

I have an array in PHP like this:

[{"pos"=0,"name"="Tom"},{"pos"=1,"name"="John"},{"pos"=2,"name"="Tom"}]

I want to remove duplicates in this array based on "name". In other words, I want to get an array like this:

[{"pos"=0,"name"="Tom"},{"pos"=1,"name"="John"}]

How can we do this?

Upvotes: 0

Views: 97

Answers (1)

Emissary
Emissary

Reputation: 10148

$unique = array();
$arr = array_filter($arr, function($v) use(&$unique){
    $inArray = in_array($v->name, $unique);
    if(!$inArray) $unique[] = $v->name;
    return !$inArray;
});

demo

Upvotes: 1

Related Questions