首页 > 解决方案 > 使用 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;

它所做的只是将它添加到数组的末尾,而不是更正值来代替数组文件。

标签: php

解决方案


首先,您需要将您的 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.

您只需要考虑数组格式。如果键存在,那么您可以更新值,否则它将是数组中的新键。希望它可以帮助你。


推荐阅读