如何在.JSON文件中添加JSON数组


How to add to JSON array in .json file

如何添加到PHP的。json文件?目前,我正在用PHP附加一个. JSON文件,但它不会将数据添加到现有的JSON对象中。它生成一个新对象。我需要的数据都存储在一个对象,在一个外部JSON文件。基本上,我有一个JSON对象,并希望向其添加更多值。

$jsonFile = "test.json";
$fh = fopen($jsonFile, 'w');
$json = json_encode(array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it));
fwrite($fh, $json);

您可以将json文件解码为php数组,然后插入新数据并再次保存。

<?php
$file = file_get_contents('data.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[] = array('data'=>'some data');
//save the file
file_put_contents('data.json',json_encode($data));
unset($data);//release memory

以上建议是最困难的方法。我正在考虑应该有一个更简单的方法,字面上附加一个数组到json文件。

算法如下:

$handle=fopen($jsonFile);
fseek($handle,-1,SEEK_END);
fwrite($handle,$arrayToAdd);
fclose($handle);

,但我不确定它是更多的cpu/内存效率这样做比读取整个json文件到内存中,添加数组,然后得到它的存储。