Search code examples
phpduplicateson-duplicate-keyarrays

Once more about removing duplicate values from a multi-dimensional array in PHP


After an exhausting search I found some similar problems like the one I would like to solve, but I could not use their answers.

Hier are some very good examples:

How to remove duplicate values from a multi-dimensional array in PHP

How to remove duplicate values from a multi-dimensional array in PHP

How to remove duplicate values from a multi-dimensional array in PHP revisited

This one is the most similar, but the answer somehow doesn't work to me.

php filter array values and remove duplicates from multi dimensional array

The main difference to my issue is that while people are looking for a solution to delete an entire duplicated subarray from the array, I'm trying to delete the subarray when only one $key => $value pair of the subarray is similar to the correspondent pair of another subarray. The other pairs could have different values or even the same.

Here my array:

Array(

[0] => Array
    (
        [0] => AAA
        [1] => 500
    )

[1] => Array //Won't be delete 'cause [0] is different, although [1] is the same.
    (
        [0] => BBB
        [1] => 500
    )

[2] => Array //Will be delete 'cause [0] is the same.
    (
        [0] => AAA
        [1] => 500
    )

[3] => Array //Won't be delete 'cause [0] is different.
    (
        [0] => CCC
        [1] => 820
    )

[4] => Array
    (
        [0] => AAA //Will be delete 'cause [0] is the same. [1] is also different.
        [1] => 774
    )

How could I manage to delete these subarrays so I have following result:

Array(

[0] => Array
    (
        [0] => AAA
        [1] => 500
    )

[1] => Array
    (
        [0] => BBB
        [1] => 500
    )

[2] => Array
    (
        [0] => CCC
        [1] => 820
    )

Many thanks in advance!


Solution

  • The easiest solution (in my opinion), instead of using magical array_filter and array_map handicraft which is difficult to maintain, is to write a specialized function yourself:

    $out = [];
    $usedKeys = [];
    foreach ($in as $element)
    {
        list ($a, $b) = $element;
        if (!isset($usedKeys[$a]))
        {
            $usedKeys[$a] = true;
            $out[]= $element;
        }
    }
    var_dump($out);
    

    This will return only elements whose first pair element is unique (taking first one, if multiple entries are available).