Recursion doesn’t seem to be necessary for the “parent” direct values, so that can be done with a direct foreach loop.
The “children” indirect values require recursion. I’ve elected to use array_walk_recursive()
to access every “leaf node” in the array. This will also store the parents’ indirect values too, so I subtract those values after array_walk_recursive()
is finished.
Code: (Demo)
$result['sum_direct'] = 0;
$result['sum_indirect'] = 0;
$parents_indirect = 0;
echo "<pre>";
$array = json_decode($json, true)['users'];
foreach ($array as $users) {
$result['sum_direct'] += $users['package'][1]['direct'];
$parents_indirect += $users['package'][2]['indirect'];
}
array_walk_recursive($array, function ($v, $k) use (&$result) {
if ($k === 'indirect') {
$result['sum_indirect'] += $v;
}
});
$result['sum_indirect'] -= $parents_indirect;
echo json_encode($result);
Output using your in-question data:
{"sum_direct":400,"sum_indirect":3000}
Output using your full json from github:
{"sum_direct":600,"sum_indirect":22400}
10
solved How to use recursion to sum specific values in a multidimensional array?