sergiodebcn sergiodebcn - 26 days ago 15
PHP Question

Multidimensional Array delete duplicated key values with condition

I have an Array Like this:

$ratesData = [
1 => [
'id' => 1,
'amount' => 2
],
0 => [
'id' => 1,
'amount' => 1
],
2 => [
'id' => 1,
'amount' => 3
],
3 => [
'id' => 2,
'amount' => 2
]
];


I want to keep the duplicated id arrays with cheapest amount, the result will be like this:

[
0 => [
'id' => 1,
'amount' => 1
],
1 => [
'id' => 2,
'amount' => 2
]
]


I have a code that works with this problem, but I'm searching an elegant way to accomplish this without all this loops:

foreach($ratesData as $firstLoopKey => $firstLoopValue) {
foreach($ratesData as $secondLoopKey => $secondLoopValue) {
if($firstLoopValue['id'] === $secondLoopValue['id'] && $firstLoopKey != $secondLoopKey ) {
if ($ratesData[$secondLoopKey]['total_amount'] > $ratesData[$firstLoopKey]['total_amount']) {
$deleteElements[] = $secondLoopKey;
}
}
}
}

if (isset($deleteElements)) {
foreach ($deleteElements as $element) {
unset($ratesData[$element]);
}
}

$ratesData = array_values($ratesData);

return $ratesData;

Answer Source

You can sort by amount descending and then extract the array indexing by id which will eliminate the duplicates with the lowest amount overwriting the higher:

array_multisort(array_column($ratesData, 'amount'), SORT_DESC, $ratesData);
$ratesData = array_column($ratesData, null, 'id');

Yields:

Array
(
    [1] => Array
        (
            [id] => 1
            [amount] => 1
        )
    [2] => Array
        (
            [id] => 2
            [amount] => 2
        )
)

I always like having the key the same as a unique id to make array access/sorting easier, but you can re-index if needed:

$ratesData = array_values($ratesData);