分组和求和多维数组

时间:2019-12-12 15:14:43

标签: php

嗨,我有以下多维数组:

Multi-dimensional array

我想按CustID分组并求和0_days,三十_60 ..etc

我可以将总数相加如下:

$zero_30 = array_sum(array_column($aging,'zero_30'));
$thirty_60 = array_sum(array_column($aging,'thirty_60'));
$sixty_90 = $array_sum(array_column($aging,'sixty_90'));
$ninety_plus = array_sum(array_column($aging,'ninety_plus'));

但是我不确定如何生成一个数组,其中每个CustID的总和为总和?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

$result = [];
foreach ($array as $data) {

    $custID = $data->CustID;

    // If you don't have the current CustID : you create it and add all data
    if (!isset($result[$custID])) {
        $result[$custID] = $data;
    } 
    // Now if you have one entry : you just sum the data with the one you already have
    else {
         $result[$custID]->zero_days   += $data->zero_days;
         $result[$custID]->thirty_60   += $data->thirty_60;
         $result[$custID]->sixty_90    += $data->sixty_90;
         $result[$custID]->ninety_plus += $data->ninety_plus;
    }
}