我想在JSON中修改一个值。假设我有这个示例JSON,并且我想让php更改电话号码:
$data = '{
"firstName": "John",
"lastName": "Smith",
"age": 27,
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
}
]
}'
听起来我必须使用json解码转换为数组:
$data = json_decode($data,true);
哪个给我这个:
array (
'firstName' => 'John',
'lastName' => 'Smith',
'age' => 27,
'phoneNumbers' =>
array (
0 =>
array (
'type' => 'home',
'number' => '212 555-1234',
),
),
)
然后如何将自己的变量值插入数组?从我的谷歌搜索看来,我可能正沿着正确的道路走上正确的道路:
$number = '50';
$data[$key]['age'] = $number;
但是,它只是将其添加到数组的末尾,而不是在数组文件的位置校正该值。
答案 0 :(得分:1)
首先,您需要将json转换为usign json_decode
函数的PHP数组。检查以下代码以更新/插入密钥:
$data['age'] = $number; // to update age
$data['newkey'] = 'newvalue'; //it will add key as sibling of firstname, last name and further
$data['phoneNumbers'][0]['number'] = '222 5555 4444'; //it will change value from 212 555-1234 to 222 5555 4444.
您只需要考虑数组格式。如果键存在,则可以更新值,否则它将是数组中的新键。希望对您有帮助。