php - 使用 PHP 更改数组的就地值
问题描述
我想修改 JSON 中的一个值。假设我有这个示例 JSON,我想让 php 更改电话号码:
$data = '{
"firstName": "John",
"lastName": "Smith",
"age": 27,
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
}
]
}'
听起来我必须使用 json decode 转换为数组:
$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;
它所做的只是将它添加到数组的末尾,而不是更正值来代替数组文件。
解决方案
首先,您需要将您的 json 转换为 PHP 数组 usignjson_decode
函数。检查以下代码以更新/插入密钥:
$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.
您只需要考虑数组格式。如果键存在,那么您可以更新值,否则它将是数组中的新键。希望它可以帮助你。
推荐阅读
- swift - 制作 URLRequest 时出现 Swift 随机 400 错误
- python - 在 Python 中排序和交换元组/元组值
- reactjs - 反应 safeSetState - 反模式或良好实践?
- c++ - Qt Graphics,向前或向后移动对象
- node.js - mongoose findById 查询未执行
- mysql - 如何比较 HQL 中的时间戳字段?
- python - 使用循环更新嵌套字典中的预先存在的值
- powershell - PowerShell 属性问题
- php - php循环内的html表单
- jquery - jQuery opacity/fade animation only works once