【发布时间】:2014-09-05 08:27:15
【问题描述】:
我的场景是这样的,我从 mysql 表中获取了一个巨大的数据集
$data = $somearray; //say the number of records in this array is 200000
我正在循环这些数据,处理一些功能并将这些数据写入一个 excel 文件
$my_file = 'somefile.csv';
$handle = fopen($my_file, 'w') or die('Cannot open file: ' . $my_file); file
for($i=0;$i<count($data);$i++){
//do something with the data
self::someOtherFunctionalities($data[$i]); //just some function
fwrite($handle, $data[$i]['index']); //here iam writing this data to a file
}
fclose($handle);
我的问题是循环内存耗尽......它显示“致命错误允许的内存大小为..”无论如何都可以在不耗尽的情况下处理这个循环
由于服务器限制,我无法像这样增加 php 内存限制
ini_set("memory_limit","2048M");
我不关心它需要的时间..即使需要几个小时..所以我做了set_time_limit(0)
【问题讨论】:
-
不能批量读取 MySQL 数据或者逐行处理,而不是将整个集合保存到变量中吗?
-
我也尝试过批处理...但它仍然挂起...有什么办法可以在每个循环结束时释放内存
-
释放内存只需将变量设置为null,垃圾收集器应该处理内存。
-
是否需要将所有数据提取到内存中?你不能一次取一行吗?
-
您是否使用 PDO 来获取数据?
标签: php loops memory-management out-of-memory