I have an array, with a structure similar to that below. Where there is a heirarchy
[2] => Array
(
[sumW] => 200.39
[child] => Array
(
[3] => Array
(
[sumW] => 300.00
)
[4] => Array
(
[sumW] => 100.28
[child] => Array
(
[5] => Array
(
[sumW] => 600
)
[6] => Array
(
[sumW] => 150
)
)
)
[7] => Array
(
[sumW] => 30.00
[child] => Array
(
[8] => Array
(
[sumW] => 100.00
)
)
)
)
)
```
I can't figure out how to sum each array at EACH level of the array. So that each level has the sum of ITSELF AND the levels BELOW it.
So, for example, something like
[2] = [tot] => 1480.67
[3] = [tot] => 300.00
[4] = [tot] => 850.28
[5] = [tot] => 600.00
[6] = [tot] => 150.00
[7] = [tot] => 130.00
[8] = [tot] => 100.00
And so forth.
The array can be infinite levels deep, this only show 3 levels, but my hierarchy could extend deeper than 3 levels.
I've tried messing with array sum and with setting parent/child IDs in an array. The best I can do is get the values for 2->3,4,7. But I can't get [2] to include values form [5] and [6] and beyond.
EDIT:
Here is one approach I tried. I have parent_ids and category_ids from my raw data. And this got my sums 1 level deep at each level. But doesn't sum everything down the hierarchy.
$tot=[];
$getSum = function ($array, $pid = null) use (&$getSum, &$tot) {
$rpt = new Report;
foreach ($array as $item) {
// This returns my database value for this category.
$sum = $rpt->getCategoryTotal($item->category_id);
if($item->parent_id == $pid) {
if(!isset($tot[$item->category_id])){
$tot[$item->category_id] = $sum;
}
if(isset($tot[$item->parent_id])){
$tot[$item->parent_id] += $sum;
}
$child = $getSum($item->children, $item->category_id);
}
}
return $sum;
};
$result = $getSum($myDbData);
return dd($tot);