需要在每个子json数组中递归地插入新的键值对



我有一个嵌套的json对象数组:

$json_url_data = [{
"form_name": "z1",
"name":"name1",
"children": [{
"form_name": "z2",
"name":"name2",
"children": [{
"form_name": "z3",
"name":"name2"
}]
}]
}]

我想动态插入一个新的键值对,它应该看起来像这样:

[{
"form_name": "z1",
"name":"name1",
"peopleCount": "125,678,190",
"children": [{
"form_name": "z2",
"name":"name2",
"peopleCount": "156,987",
"children": [{
"form_name": "z3",
"name":"name2",
"peopleCount": "678,098"
}]
}]
}]

我试着使用下面这样的递归,但没能达到上面的结果:

function print_data($menu,  $depth) {
foreach ($menu as $value) {
$deepid =  '"'.$value['form_name'].'"';
$api_call_var = '{{i have a apiu call proxy here}}';
$read_data = file_get_contents($read_data);
$read_data = json_decode($read_data, true);
$value['peopleCount'] = $read_data['count']; // after decode read the count
$obj_array[] = $value;
if (is_array($value['children'])) {
print_data ($value['children'],$depth+1);
}
}//end of for each
}//end of function
print_data ($json_url_data,  0);

我被困了好几个小时,任何帮助都将不胜感激。

这应该可以解决您的问题。当更新同一个数组时,您需要接收参数作为引用,并在递归中更新同一数组。

这是代码。我添加了123作为peopleCount,但您使用API调用添加值。

<?php
echo "<pre>";
$json_url_data = json_decode('[{
"form_name": "z1",
"name":"name1",
"children": [{
"form_name": "z2",
"name":"name2",
"children": [{
"form_name": "z3",
"name":"name2"
}]
}]
}]', true);
function print_data(&$menu) {
foreach($menu as &$value) {
$value['peopleCount'] = 123; // using some API call add peopleCount value here
if(isset($value['children'])) {
print_data($value['children']);
}
}
return $menu;
}
print_r(print_data($json_url_data));

这就是输出。

Array
(
[0] => Array
(
[form_name] => z1
[name] => name1
[children] => Array
(
[0] => Array
(
[form_name] => z2
[name] => name2
[children] => Array
(
[0] => Array
(
[form_name] => z3
[name] => name2
[peopleCount] => 123
)
)
[peopleCount] => 123
)
)
[peopleCount] => 123
)
)
$arr = json_decode('[{
"form_name": "z1",
"name":"name1",
"peopleCount": "125,678,190",
"children": [{
"form_name": "z2",
"name":"name2",
"peopleCount": "156,987",
"children": [{
"form_name": "z3",
"name":"name2",
"peopleCount": "678,098"
}]
}]
}]', TRUE);
function countTotal($data) {
if(is_array($data)){
foreach($data as $row){
$row['peopleCount'] = 0;///here total val
if(isset($row['children']) {
countTotal($row['children']);
}
}
}
else {
$data['peopleCount'] = 0;//here total val
}
}
countTotal(&$arr);

最新更新