How to sum array value of duplicate data

前端 未结 5 1382
滥情空心
滥情空心 2020-12-20 01:41

I have an array with some of same ID value as shown in below.

[
    {\"ID\":\"126871\",\"total\":\"200.00\",\"currency\":\"USD\",\"name\":\"John         


        
5条回答
  •  情话喂你
    2020-12-20 02:18

    What: Create an array that is grouped by 'ID' and 'Currency'. Accumulate currency for duplicates.

    How:

    • Add rows one at a time to an output array.
    • If group is not in the array then add it
    • If it is in the array then add the currency to the existing record.

    Demonstration at eval.in

    Code:

    /** ----------------------------------------------
    * Create an output array one row at a time.
    * 
    * Group by Id and currency.   
    * 
    * @param array $groups
    * 
    * @return array
    */
    function getCurrencyGroups(array $groups)
    {
        $currencyGroups = array();
    
        foreach ($groups as $item) {
    
            $id       = $item['ID'];
            $currency = $item['currency'];
            $amount   = $item['total'];
    
            if (!isset($currencyGroups[$id][$currency])) {
                $currencyGroups[$id][$currency] = $amount;
            }
            else {
                $currencyGroups[$id][$currency] += $amount;
            }
        }
    
        return $currencyGroups;
    }
    

    Run it:

    $currencyGroups = getCurrencyGroups($source);
    

    Output:

    array (size=2)
      126871 => 
        array (size=1)
          'USD' => string '200.00' (length=6)
    
      126872 => 
        array (size=2)
          'Euro' => float 4000
          'USD' => string '500.00' (length=6)
    

提交回复
热议问题