I have a json string
$json = '{
"id": 1,
"label": "Beef",
"sector_page_id": null,
"value": 0,
"tree_children": [
{
"id": 46,
"label": "Beef",
"sector_page_id": null,
"value": 0,
"tree_children": [
{
"id": 47,
"label": "Beef - UK",
"sector_page_id": null,
"value": 15,
"tree_children": []
},
{
"id": 48,
"label": "Beef - Europe",
"sector_page_id": null,
"value": 25,
"tree_children": []
},
{
"id": 49,
"label": "Beef - Rest of World",
"sector_page_id": null,
"value": 0,
"tree_children": []
}
]
}]
}' ;
The sum of each tree_children
value will be updated on parent value, So the updated json will be like this :
$json = '{
"id": 1,
"label": "Beef",
"sector_page_id": null,
"value": 40,
"tree_children": [
{
"id": 46,
"label": "Beef",
"sector_page_id": null,
"value": 40,
"tree_children": [
{
"id": 47,
"label": "Beef - UK",
"sector_page_id": null,
"value": 15,
"tree_children": []
},
{
"id": 48,
"label": "Beef - Europe",
"sector_page_id": null,
"value": 25,
"tree_children": []
},
{
"id": 49,
"label": "Beef - Rest of World",
"sector_page_id": null,
"value": 0,
"tree_children": []
}
]
}]
}' ;
My progress is not upto the mark but still want to share the snippet Snippet Link
$obj = json_decode($json, 1);
array_walk_recursive($obj, function(&$item, $key) use($obj){
$sum = 0;
array_walk_recursive($obj, function($item1, $key1) use (&$sum){
if($key1 == 'value'){
$sum = $item1;
}
});
if($key == 'value'){
if($item == 0){
$item = $sum;
}
}
});
print_r($obj);
CodePudding user response:
Like below?
$obj = json_decode($json, 1);
function recursive_sum (&$obj) {
if ( count($obj["tree_children"]) == 0 ) {
return $obj["value"];
}
foreach ( $obj["tree_children"] as &$_obj )
$obj["value"] = recursive_sum($_obj);
return $obj["value"];
}
recursive_sum($obj);
print_r($obj);
CodePudding user response:
My working snippet
function recursive_sum (&$arr, $sum = 0){
if(isset($arr['tree_children']) && !empty($arr['tree_children'])){
foreach($arr['tree_children'] as &$eachChild){
$sum = $eachChild['value'];
$arr['value'] = recursive_sum ($eachChild, $sum);
}
}
return $sum;
}