如何读取json数组并向其中添加/合并新元素?
我的文件data.json
的内容看起来像这样的数组:
[["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]]
新元素数组示例:
Array ( [0] => Array ( [0] => 2015-11-24 20:54:28 [1] => 177 ) )
我使用了explode()
和file()
,但失败了(索引1的分隔符..).
有人有其他想法或这是正确的解决方法吗?
首先,您需要将JSON内容作为字符串导入到应用程序中,这可以通过file_get_contents()
来完成。
之后,您必须通过json_decode()
将JSON格式解码或"翻译"为PHP原语。结果将是要处理的预期数组。
然后,您可以使用[]
后缀(例如$a[] = $b;
)将一个新项目附加到该数组中
下面举例说明这三个步骤。
// get raw json content
$json = file_get_contents('data.json');
// translate raw json to php array
$array = json_decode($json);
// insert a new item to the array
$array[] = array('2015-11-24 20:54:28', 177);
为了更新原始文件,您必须通过json_encode()
将PHP原语编码为JSON,并可以通过file_put_contents()
将结果写入所需文件。
// translate php array to raw json
$json = json_encode($array);
// update file
file_put_contents('data.json', $json);
<?php
$c = file_get_contents('data.json');
// <- add error handling here
$data = json_decode($c, true);
// <- add error handling here, see http://docs.php.net/function.libxml-get-errors
参见http://docs.php.net/file_get_contents和http://docs.php.net/json_decode