marknt15 marknt15 - 1 year ago 50
PHP Question

PHP compute total of nested array

Hi I have this example array. I wanted to compute for the total the areas then add it to the parent total plus the location's individual total. So First location total will be "11" because 7 + 4. Then the "State" parent will do the same also so 10(1st state parent) + 11 (1st child) + 10 (2nd child) = 31.

$arr = array(
array(
'type' => 'state', 'total' => '10',
'location' => array(
array(
'type' => 'location', 'total' => '4',
'area' => array(
array('type' => 'area', 'total' => '6'),
array('type' => 'area', 'total' => '1')
)
),
array(
'type' => 'location', 'total' => '5',
'area' => array(
array('type' => 'area', 'total' => '2'),
array('type' => 'area', 'total' => '3')
)
)
)
),

array(
'type' => 'state', 'total' => '20',
'location' => array(
array(
'type' => 'location', 'total' => '4',
'area' => array(
array('type' => 'area', 'total' => '8'),
array('type' => 'area', 'total' => '7')
)
)
)
)
);


The desired correct output now should be recreated as:

$arr_FINAL = array(
array(
'type' => 'state', 'total' => '31',
'location' => array(
array(
'type' => 'location', 'total' => '11',
'area' => array(
array('type' => 'area', 'total' => '6'),
array('type' => 'area', 'total' => '1')
)
),
array(
'type' => 'location', 'total' => '10',
'area' => array(
array('type' => 'area', 'total' => '2'),
array('type' => 'area', 'total' => '3')
)
)
)
),

array(
'type' => 'state', 'total' => '39',
'location' => array(
array(
'type' => 'location', 'total' => '19',
'area' => array(
array('type' => 'area', 'total' => '8'),
array('type' => 'area', 'total' => '7')
)
)
)
)
);


On-going unfinished solution as per CBroe's request:

// country > state > location > area
foreach ($arr as $k => $v) {
foreach ($v['location'] as $k2 => $v2) {
foreach ($v2['area'] as $k3 => $v3) {
echo $v3['total'] . ",";
$ctr_area[] = $v3['total'];

}
$arr2[$k]['location'][$k2]['total'] += array_sum($ctr_area);
$ctr_location[] = $v2['total'];
$ctr_area = array();
}
$arr2[$k]['total'] += array_sum($ctr_location);

$ctr_state[] = $v['total'];
$ctr_location = array();
}

Answer Source

try this:

for($i = 0; $i < count($arr); $i++){ 
$state_total = $arr[$i]["total"];    
for($j = 0; $j < count($arr[$i]['location']); $j++){
    $location_total = $arr[$i]['location'][$j]["total"];
    for($k = 0; $k < count($arr[$i]['location'][$j]['area']); $k++){
        if(isset($arr[$i]['location'][$j]['area'][$k])){
            $location_total = $location_total + $arr[$i]['location'][$j]['area'][$k]['total'];
        }
    }
    $arr[$i]['location'][$j]["total"] = $location_total;
    $state_total = $state_total + $location_total;
}
$arr[$i]["total"] = $state_total;
}

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download