我有一個 json 字串
$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": []
}
]
}]
}' ;
每個tree_children
值的總和將在父值上更新,因此更新的 json 將如下所示:
$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": []
}
]
}]
}' ;
解釋:
我的進度沒有達到標準,但仍想分享片段 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);
uj5u.com熱心網友回復:
您將使用如下遞回函式。
$obj = json_decode($json, 1);
// it is important to pass the obj by reference
function recursive_sum (&$obj) {
if ( count($obj["tree_children"]) == 0 ) {
return $obj["value"];
}
// don't forget to iterate the child using pass-by-reference &
foreach ( $obj["tree_children"] as &$_obj )
$obj["value"] = recursive_sum($_obj);
return $obj["value"];
}
recursive_sum($obj);
print_r($obj);
uj5u.com熱心網友回復:
將 json 解碼為物件非常適合此任務,因為默認情況下物件可以通過參考進行修改。換句話說,你不需要&
在變數之前顯式地寫。
遞回時無需檢查相關屬性的存在或空缺,因為樣本資料中訪問的屬性始終存在。
在每個級別中回圈tree_children
,并將遞回其子級的總和值添加到其value
.
頂層return
將提供總和,但初始函式呼叫不使用該值,因為該sum_recursive()
呼叫純粹用于修改物件。
代碼:(演示)
$obj = json_decode($json);
function sum_recursive(object $obj): int {
foreach ($obj->tree_children as $child) {
$obj->value = sum_recursive($child);
}
return $obj->value;
}
sum_recursive($obj);
var_export($obj);
uj5u.com熱心網友回復:
我的作業片段
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470938.html