如何汇总子数组元素并按子数组值分组?

时间:2019-07-16 11:48:11

标签: php multidimensional-array group-by sum

我想对子数组值求和并按子数组值分组,但出现错误:“未定义索引:EEReg”。

数组如下。

array

,当前代码为;

$total_balances = array();
foreach ($balances as $balance) {
    foreach ($balance as $key => $value) {
        if ($key == 'MemberNumber' || $key == 'Portfolio') {
            continue;
        } else {
            $total_balances[$balance['Portfolio']][$key] += $value;
        }
    }
}

我希望结果是

$total_balances = [
 "Aggressive" => [
    "EEReg" => "Sum of EEReg where Portfolio is Aggressive",
    "ERReg" => "Sum of ERReg where Portfolio is Aggressive",
],
 "Moderate" => [
    "EEReg" => "Sum of EEReg where Portfolio is Moderate",
    "ERReg" => "Sum of ERReg where Portfolio is Moderate",
]
]

1 个答案:

答案 0 :(得分:0)

您只需要使用一次foreach,并且还需要在使用$ total_balance数组之前定义它们。请参见下面的代码

$total_balances = array();
foreach ($balances as $balance) {
    if( !isset( $total_balances[$balance['Portfolio']] )) {
        $total_balances[$balance['Portfolio']] = array('EEREG' => 0, 'ERREG' => 0); 
    }
    $total_balances[$balance['Portfolio']]['EEREG'] += $balance['EEREG'];
    $total_balances[$balance['Portfolio']]['ERREG'] += $balance['ERREG'];
}