更新现有的JSON

时间:2016-02-22 12:41:26

标签: php json

假设我有以下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"
      }
   ]
}

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

2 个答案:

答案 0 :(得分:1)

你需要遍历你的数组。在您循环对象的那一刻,第一个项目是employees,然后没有更多的项目。

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

答案 1 :(得分:-2)

这取决于您使用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

for 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;
};