如何使用 PHP 更新/编辑 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17806224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:29:44  来源:igfitidea点击:

How to update/edit a JSON file using PHP

phpjson

提问by user475464

Here is my JSON

这是我的JSON

[
   {
      "activity_code":"1",
      "activity_name":"FOOTBALL"
   },
   {
      "activity_code":"2",
      "activity_name":"CRICKET"
   }
]

I need to update {"activity_code":"1","activity_name":"FOOTBALL"}to {"activity_code":"1","activity_name":"TENNIS"}based on activity_code

我需要更新{"activity_code":"1","activity_name":"FOOTBALL"}{"activity_code":"1","activity_name":"TENNIS"}基于activity_code

How can I achieve this in PHP?

我怎样才能在 PHP 中实现这一点?

回答by Brewal

First, you need to decode it :

首先,您需要对其进行解码:

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

Then change the data :

然后更改数据:

$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
    if ($entry['activity_code'] == '1') {
        $data[$key]['activity_name'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

然后重新编码并将其保存回文件中:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);