3

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],
];
2
  • FYI, you keep using the term "key", but you area actually referring to a "value", not a "key". The [0], [2], and [5] you mention are keys. The [ID] is also a key. The 9 that each of these ID's contains are all values. Commented Dec 1, 2010 at 22:28
  • thanks, i have modified the language of the question. Commented Dec 1, 2010 at 22:42

6 Answers 6

6

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)

Sign up to request clarification or add additional context in comments.

Comments

3

You can do it with ouzo goodies:

$result = FluentArray::from($array)->uniqueBy('ID')->toArray();

See http://ouzo.readthedocs.org/en/latest/utils/fluent_array.html#uniqueby

Comments

0

I think it would be easiest to loop through and construct a new array. In the loop, use array_key_exists() to determine if the ID already exists in the new array, and if not, append an element.

Comments

0

It is not a multidimensional array, it is an array of objects. You can just loop over it (this example changes the array in place):

$ids = array();

forach($array as $key=>$obj) {
    if(isset($ids[$obj->ID])) {//did we already encounter an object with this ID?
        unset($array[$key]); // if yes, delete this object
    }
    else {
        $ids[$obj->ID] = 1; // if not, add ID to processed IDs
    }
}

You can also create a new array and add the objects to the new array.

Comments

0
foreach ($array as $element) {
    foreach ($array as &$element2) {
        if ($element2->ID == $element->ID && $element2 != $element) {
            unset($element2);
        }
    }
}

Note the loop-by-reference in the second foreach.

Comments

0

Check indexed function from Nspl.

use function \nspl\op\propertyGetter;
use function \nspl\a\indexed;

$groupedById = indexed($objects, propertyGetter('id'));

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.