PHP - 加载JSON,编辑并保存

时间:2014-02-12 15:02:04

标签: php json

我从文件中加载JSON:

{ "timestampRead": [11, 22, 33], "timestampCurrent": [66, 77, 88] }

到PHP:

$local_json = json_decode(file_get_contents('/Temp/chat-users.json'));

我不知道怎么做:

  1. 更新timestampRead($local_json->timestampRead[] = '99'?
  2. 中的所有值
  3. 更新timestampCurrent($local_json->timestampCurrent[2] = '33'
  4. 中的一个值
  5. 将更新的json保存到文件($local_json array to json

2 个答案:

答案 0 :(得分:2)

1)更新timestampRead中的所有值:$local_json->timestampRead = array( [your comma separated values] );

2)更新timestampCurrent中的一个值:$local_json->timestampCurrent[2] = '33';(正确)

3)将更新后的json保存到文件:file_put_contents('path/to/file', json_encode($local_json));

答案 1 :(得分:1)

将json数据加载到变量后,您可以像访问普通类一样访问每个属性:

$local_json->timestampRead = $new_timestampRead;
$local_json->timestampCurrent[an_index] = "whatever you want";

要将数据保存回文件,您可以使用名为file_put_contents()file_get_contents()的计数器部分:

file_put_contents("path/to/file", $local_json);