假设我具有以下JSON结构:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
如何使用PHP更新它并添加另一个属性,例如age?
这是我的预期结果:
{"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"
}
]
}
因此,它仅将其添加到第一项。
您需要遍历数组。目前,您正在遍历对象,因此第一个项目是employees
,然后没有更多项目。
foreach ($data1['employees'] as $key => $entry) {
$data1['employees'][$key] += $data2["employees"][$key];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句