我想在每一個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
作爲輸出,沒有新的鍵值對。
的[添加新的鍵/值對爲JSON在PHP]可能的複製(http://stackoverflow.com/questions/19447175/add-new-key-value-pair -in -json-in-php) – Core972
@Core972不是重複的。 –
通過引用迭代數組 – Steve