我有一个260k行的csv文件,它有两列。我已经使用fgetcsv读入了csv文件,并使用了一个while循环来读取文件中的每一行。在循环中,我尝试将第二列中的值添加到数组中。
当我有要添加到数组中的行时,我的PHP冻结并且没有完成。我已经完成了调试,并且值被添加到数组中,所以我知道添加到数组和while循环可以工作,但我不知道它为什么会冻结。
如果我删除这一行,while循环将完成对26万行的遍历,然后处理文件的其余部分。
下面是我的代码:
$amountRecords = 0;
$totalValue = 0;
$valueArray = array();
// reads in csv file
$handle = fopen('Task1-DataForMeanMedianMode.csv', 'r');
// to skip the header names/values
fgetcsv($handle);
// creates array containing variables from csv file
while(($row = fgetcsv($handle, "\r")) != FALSE)
{
/*
echo "ROW CONTAINS: ";
var_dump($row[1]);
echo "<br />";
*/
$valueArray[] = $row[1];
/*
echo "VALUEARRAY NOW CONTAINS: ";
var_dump($valueArray);
echo "<br />";
*/
$totalValue = $totalValue + $row[1];
$amountRecords++;
}和csv文件示例:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
10,55.00发布于 2012-08-20 03:48:34
对于内存不足错误,通常有两种方法。像往常一样,你可以选择容易但错误和困难但正确的选择。简单但错误的解决方案是将your memory limit增加到适当的级别:
ini_set('memory_limit', '64M');更好(虽然更难)的解决方案是重新设计算法,使其不需要那么多内存。这显然是更可持续和更健壮的方法。为了正确地做到这一点,您需要评估您需要对正在构建的数组执行哪些操作。例如,我编写了类似的脚本,将行导入到数据库中。我没有构建一个巨大的数组然后插入,而是分批进行,我构建了一个50-100行的数组,然后插入这些行并清除该数组(释放内存以供重复使用)。
伪代码:
for(each row in file) {
$rows_cache[] = $row[1];
if(count($rows_cache) >= 50) {
insert_these($rows_cache);
$rows_cache = array();
}
}发布于 2012-08-20 00:30:25
您的第一行是字符串,也许可以尝试添加
while(($row = fgetcsv($handle, "\r")) != FALSE)
{
if(is_numeric($row[1]))
{
$valueArray[] = $row[1];
$totalValue = $totalValue + $row[1];
$amountRecords++;
}
}发布于 2012-08-20 01:12:02
为什么不去掉这行:
$totalValue = $totalValue + $row[1];从您的循环内部,而不是使用:
$totalValue = array_sum($valueArray);在完成循环之后
https://stackoverflow.com/questions/12028055
复制相似问题