2

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",
]
]
1
  • You need to make sure that $total_balances[$balance['Portfolio']] actually exists before you do $total_balances[$balance['Portfolio']][$key]. If it doesn't exist yet, create it and then use it. If it does exist, just use it. Commented Jul 16, 2019 at 11:52

1 Answer 1

1

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.