使用 PHP 更改 json 文件中一对 key/value 的值

Changing the value of one key/value pair in a json file with PHP

我们有一个简单的 json 文件,我们使用存储数据并试图找出如何操作一个键的值,然后使用 json 文件保存新值 PHP.

json 文件基本上是:

{
  "stuff":"something",
  "more":"whatever",
  "name":"George",
  "about":"some string",
  "when":"tomorrow",
  many more key/value pairs
}

我们想要获取 'about' 字符串,向其附加另一个字符串,然后保存生成的更长的字符串。获取数据并附加额外的字符串不是问题。它正在保存让我难过的新字符串。

$data = json_decode($json);
foreach ($data as $key => $value) { 
  // look for about data
  if ($key == 'about') {
    $newstr = $value;
    $newstr .= ' extra string bits';
     
    // need to replace original $value with $newstr
    
  }
}

$newjson = json_encode($data);

结果 json 应该是:

{
  "stuff":"something",
  "more":"whatever",
  "name":"George",
  "about":"some string extra string bits",
  "when":"tomorrow",
  many more key/value pairs
}

我们正在使用 foreach,因为 json 文件中的其他值正在 PHP 过程中使用,但如果有其他更好的方法来处理数据检索和更新部分,我很乐意将功能分开并欢迎提出建议。

这里是:

$data = json_decode($json,true);
foreach ($data as $key => $value) { 
  // look for about data
  if ($key == 'about') {
    $newstr = $value;
    $newstr .= ' extra string bits';
    $data[$key] = $newstr;
  }
}

$newjson = json_encode($data);

无需使用foreach。当您 json_decode 您的 JSON 您可以简单地通过附加到对象来设置新值:

<?php
$json = '{
  "stuff":"something",
  "more":"whatever",
  "name":"George",
  "about":"some string",
  "when":"tomorrow"
}';
$data = json_decode($json);
$data->about .= ' extra string bits';
echo json_encode($data, JSON_PRETTY_PRINT);

将输出:

{
    "stuff": "something",
    "more": "whatever",
    "name": "George",
    "about": "some string extra string bits",
    "when": "tomorrow"
}