我试图在每个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
作为输出,没有新的键值对。
答案 0 :(得分:3)
摘自手册关于{{3}}:
为了能够直接修改循环内的数组元素 使用&amp;前面的$ 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"
}]
}]
答案 1 :(得分:0)
你的主要问题是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循环中保持键。然后,当我们有结构时,我们希望更新原始数组。
答案 2 :(得分:0)
您应该通过引用传递$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;
}