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.

9
  • Do you consider duplicate values as objects with the same id property? Which of the two given objects with id = 2 has the higher priority? Commented Feb 12, 2018 at 17:23
  • Yes as I'm going to display it in a table. Commented Feb 12, 2018 at 17:29
  • it doesn't matter if it is the second or first or whatever. Commented Feb 12, 2018 at 17:30
  • 3
    You can reindex the array by id: $unique = array_column($array, null, 'id'); (Needs PHP 7) Commented Feb 12, 2018 at 17:36
  • 2
    @Barmar To be fair, all answers in the question that you've pointed, are so rubbish... Commented Feb 12, 2018 at 17:43

1 Answer 1

1

One possible solution:

$arr = array_values(array_reduce($arr, function($arr, $x) {
    $arr[$x->id] = $x;
    return $arr;
}, []));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.