【发布时间】:2016-09-17 10:00:40
【问题描述】:
尝试在foreach 循环中使用array_combine 时遇到问题。最终会报错:
PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 85 bytes) in
这是我的代码:
$data = array();
$csvData = $this->getData($file);
if ($columnNames) {
$columns = array_shift($csvData);
foreach ($csvData as $keyIndex => $rowData) {
$data[$keyIndex] = array_combine($columns, array_values($rowData));
}
}
return $data;
我使用的源文件 CSV 大约有 ~1,000,000 行。这一行
$csvData = $this->getData($file)
我使用 while 循环来读取 CSV 并将其分配到一个数组中,它的工作没有任何问题。麻烦来自array_combine 和foreach 循环。
您是否有任何想法来解决这个问题或只是有更好的解决方案?
更新
这是读取 CSV 文件的代码(使用 while 循环)
$data = array();
if (!file_exists($file)) {
throw new Exception('File "' . $file . '" do not exists');
}
$fh = fopen($file, 'r');
while ($rowData = fgetcsv($fh, $this->_lineLength, $this->_delimiter, $this->_enclosure)) {
$data[] = $rowData;
}
fclose($fh);
return $data;
更新 2
如果您正在处理
【问题讨论】:
-
$this->getData($file)是否只读取原始文件? -
@RomanPerekhrest:是的。我将该方法添加到问题中。
-
您确定错误发生在
foreach循环内而不是$this->getData($file)操作上? -
@RomanPerekhrest:我很确定,因为记录的错误表明它来自
foreach循环中的array_combine方法。而$csvData携带的数据是正确的。