如何对子数组元素求和并按子数组值分组? [重复]

问题描述 投票:0回答:1

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

数组如下

当前代码是;

$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",
]
]
php multidimensional-array group-by sum
1个回答
1
投票

你只需要使用一次 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'];
}
© www.soinside.com 2019 - 2024. All rights reserved.