我正试图在每个users
元素的末尾添加一个新的键值对:
<?php
$json = '[
{
"date": "2014-10-09T17:38:19Z",
"users": [
{
"name": "Peter",
"age": 20
},
{
"name": "Anne",
"age": 25
},
{
"name": "William",
"age": 30
}
]
}
]';
addData ( $json );
function addData($json) {
$obj = json_decode ( $json, true );
foreach ( $obj as $items ) {
foreach ( $items ['users'] as $users ) {
$array = array (
"myKey" => "myValue"
);
array_push ( $users, $array );
}
}
$json = json_encode ( $obj );
echo $json;
}
?>
所以新的json
应该看起来像
[
{
"date":"2014-10-09T17:38:19Z",
"users":[
{
"name":"Peter",
"age":20,
"myKey":"myValue"
},
{
"name":"Anne",
"age":25,
"myKey":"myValue"
},
{
"name":"William",
"age":30,
"myKey":"myValue"
}
]
}
]
相反,我得到旧的json
作为输出,没有新的键值对。
摘自关于foreach的手册:
为了能够直接修改循环中的数组元素$value前面加&。在这种情况下,值将由参考
通过这种方式,您可以编辑$items
和$users
数组中的值。
我想你可以这样做:
addData ( $json );
function addData($json) {
$obj = json_decode ( $json, true );
foreach ( $obj as &$items ) {
foreach ( $items ['users'] as &$users ) {
$users["mykey"] = "myValue";
}
}
$json = json_encode ( $obj );
echo $json;
}
将导致:
[{
"date": "2014-10-09T17:38:19Z",
"users": [{
"name": "Peter",
"age": 20,
"mykey": "myValue"
}, {
"name": "Anne",
"age": 25,
"mykey": "myValue"
}, {
"name": "William",
"age": 30,
"mykey": "myValue"
}]
}]
您的主要问题是foreach提供了数组的副本,而不是实际的数组,所以当您修改$users时,您并没有像您认为的那样修改$json变量。试试下面的,我已经更改了变量的名称等可读性
<?php
$json = '[
{
"date": "2014-10-09T17:38:19Z",
"users": [
{
"name": "Peter",
"age": 20
},
{
"name": "Anne",
"age": 25
},
{
"name": "William",
"age": 30
}
]
}
]';
$updated = addData ( $json );
echo $updated;
function addData($json) {
$ArrList = json_decode ( $json, true );
foreach ( $ArrList['users'] as $userKey => $user ) {
$array = array (
"myKey" => "myValue"
);
$ArrList['users'][$userKey][] = $array;
}
$json = json_encode ( $ArrList );
return $json;
}
?>
上面的代码循环遍历结构中的users数组,并保持foreach循环中的键。然后,当我们有了我们想要的结构时,我们更新原始数组。
您应该通过引用传递$items
和$users
数组,如下所示:
function addData($json) {
$obj = json_decode ( $json, true );
foreach ( $obj as &$items ) {
foreach ( $items ['users'] as &$users ) {
$users['myKey'] = 'myValue';
}
}
$json = json_encode ( $obj );
echo $json;
}