PHP将文件(数组)读取为数组

PHP将文件(数组)读取为数组,php,arrays,file,Php,Arrays,File,如何读取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数组并向其中添加/合并新元素

我的文件
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\u get\u contents()
可以做些什么

<?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
之后,您必须通过
JSON\u 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\u encode()
将PHP原语编码为JSON,并可以通过
file\u put\u contents()
将结果写入所需文件


首先使用foreach,然后使用explode。是的,foreach可以站立。。
// translate php array to raw json
$json = json_encode($array);

// update file
file_put_contents('data.json', $json);