Search code examples
phpmultidimensional-arraygroup-bysum

How do I sum subarray elements and group by subarray value?


I want to sum subarray values and group by a subarray value but I am getting error: 'Undefined index: EEReg'.

The array is as follows.

array

and the current code is;

$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;
        }
    }
}

I expect the result to be;

$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",
]
]

Solution

  • You need to use foreach only once and also you need to define the keys in $total_balance array before using them. Please see below code

    $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'];
    }