php - Multidimensional Array delete duplicated key values with condition -




i have array this:

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

i want keep duplicated id arrays cheapest amount, result this:

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

i have code works problem, i'm searching elegant way accomplish without loops:

    foreach($ratesdata $firstloopkey => $firstloopvalue) {         foreach($ratesdata $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 $element) {             unset($ratesdata[$element]);         }     }      $ratesdata = array_values($ratesdata);      return $ratesdata; 

you can sort amount descending , extract array indexing id eliminate duplicates lowest amount overwriting 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 having key same unique id make array access/sorting easier, can re-index if needed:

$ratesdata = array_values($ratesdata); 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -