0

how to remove duplicates in php associative array? The array is created from JSON.

    array (size=646)
  0 => 
    object(stdClass)[1]
      public 'id' => string '1' (length=1)
      public 'name' => string 'John' (length=4)
      public 'city' => string 'NY' (length=2)

  1 => 
    object(stdClass)[3]
      public 'id' => string '2' (length=1)
      public 'name' => string 'Henry' (length=5)
      public 'city' => string 'Mexico' (length=6)
  2 => 
    object(stdClass)[5]
      public 'id' => string '2' (length=1)
      public 'name' => string 'Jordan' (length=6)
      public 'city' => string 'Lake' (length=4)
              ...

I've tried to use array_unique($data) but I'm still getting the duplicate values. I just want to get those unique elements by its id. TIA.

silent_coder14
  • 583
  • 2
  • 10
  • 38

1 Answers1

1

One possible solution:

$arr = array_values(array_reduce($arr, function($arr, $x) {
    $arr[$x->id] = $x;
    return $arr;
}, []));
VisioN
  • 143,310
  • 32
  • 282
  • 281