Reputation: 1447
I basically want to change the value of a multidimensional array by adding to the previous value.
Example:
$arr=array(1,2,3);
foreach($arr as $val){
$arrTotal[1][2][3]=$val;
}
This would make $arrTotal[1][2][3]=3
What I really want is $arrTotal[1][2][3]=6
3+2+1.
I have tried an approach like so:
$arrTotal[1][2][3]+=$val;
But to no avail.
Upvotes: 0
Views: 92
Reputation: 5754
More general solution:
<?php
function hierarchical_array_sum(array $arr) {
$parent = null;
$current = $total = new ArrayObject;
foreach ($arr as $val) {
$parent = $current;
$current = $current[$val] = new ArrayObject;
}
if ($parent !== null) {
$parent[$val] = array_sum($arr);
}
$total = json_decode(json_encode($total), true);
}
var_dump(hierarchical_array_sum(array(1, 2, 3, 4, 5, 6, 7)));
Upvotes: 1
Reputation: 76656
Easiest approach:
$arr = array(1,2,3);
$arrTotal[1][2][3] = array_sum($arr);
Upvotes: 8
Reputation: 2481
$arrTotal[1][2][3] = 0;
foreach($arr as $val){
$arrTotal[1][2][3] = $arrTotal[1][2][3] + $val;
}
Upvotes: 0