使用PHP更改数组的就地值
我想修改JSON中的一个值。假设我有这个JSON示例,我想让php更改电话号码:使用PHP更改数组的就地值,php,Php,我想修改JSON中的一个值。假设我有这个JSON示例,我想让php更改电话号码: $data = '{ "firstName": "John", "lastName": "Smith", "age": 27, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" } ] }' 听起来我必须使用json解码转换为数组: $data = json_decode($
$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;
不过,它所做的只是将其添加到数组的末尾,而不是在数组文件的位置更正值 首先,您需要使用gn
json\u decode
函数将json转换为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.
<>你只需要考虑数组格式。若键存在,那个么您可以更新值,否则它将是数组中的新键。希望对您有所帮助。
$data['age']=$number代码>和请-阅读您正在使用的编程语言的基础知识。