一尘不染

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

php

这是我的 JSON

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

我需要升级{"activity_code":"1","activity_name":"FOOTBALL"}{"activity_code":"1","activity_name":"TENNIS"}基于activity_code

如何在PHP中实现呢?


阅读 331

收藏
2020-05-29

共1个答案

一尘不染

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

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

然后更改数据:

$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";
    }
}

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

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
2020-05-29