Monday, 27 August 2018

Remove duplicates in a multidimensional array and keep the value of the original array key

I have this array
Array (
[0] => Array ( [name] => Apple [amount] => 1)
[1] => Array ( [name] => Apple [amount] => 2)
[2] => Array ( [name] => Orange [amount] => 3)
[3] => Array ( [name] => Orange [amount] => 4)
[4] => Array ( [name] => Banana [amount] => 5)
[5] => Array ( [name] => Pear [amount] => 6)
)

which i would like to end up like this:
Array (
[0] => Array ( [name] => Apple [amount] => 1)
[2] => Array ( [name] => Orange [amount] => 3)
[4] => Array ( [name] => Banana [amount] => 5)
[5] => Array ( [name] => Pear [amount] => 6)
)

The important thing is that the array key values must be the same after transforming.
At the moment i use this solution:
$newArray = array();
$usedFruits = array();
foreach ( $originalArray AS $line ) {
    if ( !in_array($line['name'], $usedFruits) ) {
        $usedFruits[] = $line['name'];
        $newArray[] = $line;
    }
}
$originalArray = $newArray;
$newArray = NULL;
$usedFruits = NULL;

This removes the duplicate arrays but it also resets the key values.
Array (
[0] => Array ( [name] => Apple [amount] => 1)
[1] => Array ( [name] => Orange [amount] => 3)
[2] => Array ( [name] => Banana [amount] => 5)
[3] => Array ( [name] => Pear [amount] => 6)
)

How is it possible to keep the original array key values?

Use the optional $key in the foreach():
foreach ( $originalArray AS $key => $line ) {
    if ( !in_array($line['name'], $usedFruits) ) {
        $usedFruits[] = $line['name'];
        $newArray[$key] = $line;
    }
}

Outputs:
Array
(
    [0] => Array
        (
            [name] => Apple
            [amount] => 1
        )

    [2] => Array
        (
            [name] => Orange
            [amount] => 3
        )

    [4] => Array
        (
            [name] => Banana
            [amount] => 5
        )

    [5] => Array
        (
            [name] => Pear
            [amount] => 6
        )

)

0 comments:

Post a Comment