这是我的 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
{"activity_code":"1","activity_name":"FOOTBALL"}
{"activity_code":"1","activity_name":"TENNIS"}
activity_code
如何在PHP中实现呢?
首先,您需要对其进行解码:
$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);