Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在单个文件中读取或写入多个JSON对象_Php_Json - Fatal编程技术网

Php 在单个文件中读取或写入多个JSON对象

Php 在单个文件中读取或写入多个JSON对象,php,json,Php,Json,我已经构建了一个脚本来刮取一些记录,并将它们存储为json对象以供以后使用。这是刮取过程的最后一步(区域->位置->ReportMeta->ReportDetails),使用这种存储数据的方法都可以正常工作 问题是它们有很多,大约有几十万。我试着把它们都累加到一个数组中,然后编码并写入一个文件,但在接近完成之前,内存已经用完了。我可以增加内存,但我正在寻找一种更稳定/可复制/开箱即用的方法。最佳实践,如果你愿意的话 我的第一个想法是把它们写进文件,因为每一个都被刮去了。这是可行的,但我只剩下一个

我已经构建了一个脚本来刮取一些记录,并将它们存储为json对象以供以后使用。这是刮取过程的最后一步(区域->位置->ReportMeta->ReportDetails),使用这种存储数据的方法都可以正常工作

问题是它们有很多,大约有几十万。我试着把它们都累加到一个数组中,然后编码并写入一个文件,但在接近完成之前,内存已经用完了。我可以增加内存,但我正在寻找一种更稳定/可复制/开箱即用的方法。最佳实践,如果你愿意的话

我的第一个想法是把它们写进文件,因为每一个都被刮去了。这是可行的,但我只剩下一个文件,其中包含许多单独的json对象,除非我做一些特殊的格式化,否则这些对象几乎无法读取

我正在寻找一个更好的方法,或者一些建议

$reports_obj = new Report();
foreach($reports_array as $report){
    $report_details = $reports_obj->getReport($report['report_id'], $report['report_type']);
    $fp = fopen('report_details.json', 'a');
    fwrite($fp, json_encode($report_details));
    fclose($fp);
}
这给我留下了一大堆这样的东西:

{
  "report_id": "12345",
  "report_type": "Type A",
  "facility_name": "Name here",
  "facility_type": "building",
  "report_date": "26-February-2018"
}
{
  "report_id": "12345",
  "report_type": "Type A",
  "facility_name": "Name here",
  "facility_type": "building",
  "report_date": "26-February-2018"
}
{
  "report_id": "12345",
  "report_type": "Type A",
  "facility_name": "Name here",
  "facility_type": "building",
  "report_date": "26-February-2018"
}
最好在事后用正确的json结构查找/替换大文件,还是有更好的存储方法?例如,我无法打开文件,重新读取数据,然后进行数组推送,因为这最终会有与将它们全部累积到一个数组中相同的限制


至于“为什么”json?这只是一种温和的偏好。如果可能的话,我想继续使用它。

也许,你可以试试这个:

$reports_obj = new Report();
foreach($reports_array as $report){
  $report_details[] = $reports_obj->getReport($report['report_id'],$report['report_type']);
}
$jsonjson=json_encode($report_details);
$report="{\"report\":".$jsonjson."}";
$fp = fopen('report_details.json', 'a');
fwrite($fp,$report);
fclose($fp);

如果您有,示例,也许我可以检查?

您应该查找NoSQL数据库

如果你不想/不能,无论出于什么原因,最好循环浏览所有报告,生成JSON并在之后写入,而不是每次打开和关闭一个文件

$result="";
   foreach($reports_array as $report){
    $report_details = $reports_obj->getReport($report['report_id'], $report['report_type']);
   $result .= json_encode($report_details)."\n\r";
}
$fp = fopen('report_details.json', 'a');
fwrite($fp,$result);
fclose($fp)

“几十万”是一个平面文件中的许多数据点,如果你想处理这些数据的话。你应该查一下数据库。数据看起来结构良好,因此SQL应该处理它,或者您可以使用文档存储。我最终会将其移动到数据库中,问题是在处理数据的过程中,每个记录都是一个单独的页面请求。在将导入数据库之前,我想将其导出到一个平面文件中,以便使用。写入数据库不应该比写入文件更糟糕。如果你想在某个时候把它放在数据库中,而你不打算对这个文件做任何事情,我会直接把它写到数据库中。