2014-02-12 74 views
0

我加载JSON文件来自:PHP - 加载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. 更新一个在timestampCurrent(值$local_json->timestampCurrent[2] = '33'
  3. 保存更新的JSON到文件($local_json array to json
+0

[如何更新/编辑以.json的可能重复文件使用PHP](http://stackoverflow.com/questions/17806224/how-to-update-edit-json-file-using-php) – vzamanillo

+0

你尝试过什么吗?它有用吗?如果不是,它以什么方式不起作用? –

+0

线索 - 1和2工作。 3 - 你认为json_decode的反面可能是什么?你认为file_get_contents的反义词可能是什么?最后的线索 - php.net –

回答

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); 
+0

$ local_json-> timestampRead = $ new_timestampRead; - 但这段代码将我的数组更改为字符串。我想要将所有数组值更改为一个新值 –

+0

@KubaŻukowski - 如果'$ new_timestampRead'是一个数组,那么将使用什么。 – Lix

+0

我知道,但在这个例子中,我必须知道这个数组有多少元素,make和...。你懂。所以我不能更改数组上的所有值? –

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));