phparraysmultidimensional-arrayfilterunique

Filter an array of objects to only keep the first occurrence of a column value


I am working with a multi-dimensional array. How can I remove duplicates by value?

In the following array, [0], [2] and [5] have the same [ID].

Is there a function that will remove any duplicate arrays based on a particular value?

In this case, I would like to remove array [2] and array [5], as they have the same [ID] as array [0].

[
    (object) ['d' => '2010-10-18 03:30:04', 'ID' => 9],
    (object) ['d' => '2010-10-18 03:30:20', 'ID' => 4],
    (object) ['d' => '2010-11-03 16:46:34', 'ID' => 9],
    (object) ['d' => '2010-11-02 03:19:14', 'ID' => 1],
    (object) ['d' => '2010-05-12 04:57:34', 'ID' => 2],
    (object) ['d' => '2010-05-10 05:24:15', 'ID' => 9],
];

Solution

  • One way to do it: ($old_array is your array, and $new_array will contain the new one, dupes removed, keyed by that ID)

    $new_array = array();
    foreach ($old_array as $item)
      if (!array_key_exists($item->ID, $new_array))
        $new_array[$item->ID] = $item;
    

    (I haven't tested this, but it should work)