Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 更新现有的JSON_Php_Json - Fatal编程技术网

Php 更新现有的JSON

Php 更新现有的JSON,php,json,Php,Json,假设我有以下JSON结构: {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} 如何使用PHP更新它并添加另一个属性,例如年龄? 这是我的预期结果: {"employees":[ {"firstName":"John", "lastN

假设我有以下JSON结构:

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
如何使用PHP更新它并添加另一个属性,例如年龄? 这是我的预期结果:

{"employees":[
    {"firstName":"John", "lastName":"Doe", "age":"20"},
    {"firstName":"Anna", "lastName":"Smith", "age":"30"},
    {"firstName":"Peter", "lastName":"Jones", "age":"40"}
]}
更新:

这是我的方法:

$json1 = '{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}';

$json2 = '{"employees":[
    {"age":"20"},
    {"age":"30"},
    {"age":"40"}
]}';

$data1 = json_decode($json1, true);
$data2 = json_decode($json2, true);

$i = 0;
foreach ($data1 as $key => $entry) {
    $data1[$key][$i] += $data2["employees"][$i];
    $i++;
}

$json1 = json_encode($data1);
echo ($json1)
但不幸的是,我只能得到这样的结果:

{  
   "employees":[  
      {  
         "firstName":"John",
         "lastName":"Doe",
         "age":"20"
      },
      {  
         "firstName":"Anna",
         "lastName":"Smith"
      },
      {  
         "firstName":"Peter",
         "lastName":"Jones"
      }
   ]
}

因此,它只将其添加到第一个条目中。

这取决于您使用的json文件的语言,但基本上是一个

for employe in json['employees']:
    employe['age'] = '20'
但对于这种方法,所有员工的年龄都是20岁,我会做如下事情:

ages ={'John':'20','Anna':'30','Peter':'40'}
for employe in json['employess']:
   name = employe['firstname'] 
   age= ages[name]
   employe[name] = age
对于javascript:

var ages ={'John':'20','Anna':'30','Peter':'40'}
for(var i=0;i<json['employees'].length;i++){
    var employe = json['employees'][i];
    var name = employe[name];
    var age = ages[name];
    employe[name] = age;
}; 

您需要在阵列上循环。此时,您正在对象上循环,因此第一个项目是employees,然后就没有其他项目了

foreach ($data1['employees'] as $key => $entry) {
    $data1['employees'][$key] += $data2["employees"][$key];
}

解析它。修改生成的数组。序列化它。有什么问题吗?@close投票者该问题的编辑质量尚可。这取决于您使用的语言-该问题被标记为PHP