PHP: function to group an array of objects by value

I work with a multidimensional array. How to 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 specific value? In this case, I would like to delete array [2] and array [5], since they have the same [ID] as array [0].

Thank you for any information you may have.

        Array
(
    [0] => stdClass Object
        (
            [d] => 2010-10-18 03:30:04
            [ID] => 9
        )

    [1] => stdClass Object
        (
            [d] => 2010-10-18 03:30:20
            [ID] => 4
        )

    [2] => stdClass Object
        (
            [d] => 2010-11-03 16:46:34
            [ID] => 9
        )

    [3] => stdClass Object
        (
            [d] => 2010-11-02 03:19:14
            [ID] => 1
        )

    [4] => stdClass Object
        (
            [d] => 2010-05-12 04:57:34
            [ID] => 2
        )    

    [5] => stdClass Object
        (
            [d] => 2010-05-10 05:24:15
            [ID] => 9
        )

)
+3
source share
6 answers

One way to do this: ( $old_array- this is your array, but it $new_arraywill contain a new one; deleted ones are deleted using this identifier)

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

(I have not tested this, but it should work)

+5

ouzo goodies:

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

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

+3

, . array_key_exists(), , , , .

0

, . ( ):

$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
    }
}

.

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

foreach.

0

indexed Nspl.

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

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

Source: https://habr.com/ru/post/1778005/


All Articles