I have need to calculate the sum of the deep elements foreach first level element.
Sample 3-level array:
[
1 => [
'A' => ['AA' => 3, 'AB' => 5],
'B' => ['BA' => 2]
],
2 => [
'C' => ['CA' => 4],
'D' => ['DA' => 1, 'DB' => 2]
],
3 => [
'E' => ['EA' => 1, 'EB' => 2, 'EC' => 3],
'F' => ['FA' => 0, 'FB' => 7, 'FC' => 7]
]
]
I want to sum the values and this is my expectation:
Array(
[1] => 10
[2] => 7
[3] => 20
)
Here is my code that I used for summing the value:
$total[$country_id][$province_id][$city_id] = $amount;
$result = array();
foreach( $total as $key => $val ){
$total[$key] = array_sum ( $val );
}
Can someone explain what is wrong with my code or explain how foreach work? The result of my code is 0 and actually I just studied around 1 week about foreach.