【发布时间】:2020-01-02 23:36:05
【问题描述】:
我正在导入一个可能有大约 100,000 行的 csv。每行有 5 列。每行的第一列将有一个句子,其他 4 列有数值。我需要遍历 csv 数据并从每一行中获取每个单词并将其作为它自己的行添加到新数组中。比如:
| big red truck | 5 | 2 | 5 | 1 |
| small red truck | 4 | 2 | 0 | 0 |
| big fast truck | 3 | 2 | 4 | 1 |
变成
| truck | 12 | 6 | 9 | 2 |
| red | 9 | 4 | 5 | 1 |
| fast | 3 | 2 | 4 | 1 |
| small | 4 | 2 | 0 | 0 |
这就是我目前正在做的事情。它适用于较小的文件,但在大约 50,000 行时我遇到了问题并开始恢复服务器错误。
function get_csv_terms($csvdata){
$terms = array();
$csv_rows = count($csvdata);
$x = 0;
//get terms
while($x <= $csv_rows){
$groupTerm = explode(' ', $csvdata[$x][0]);
foreach( $groupTerm as $term ){
if($term != NULL){
if(!in_array($term, $terms)){
$terms[] = $term;
}
}
}
$x++;
}
return $terms;
}
//filter csv and create data for table output
function filter_csv($csvdata){
$sortedData = array();
$csv_rows = count($csvdata);
$terms = get_csv_terms($csvdata);
$terms_count = count($terms);
$x = 0;
while($x <= $terms_count){
$y = 0;
while($y <= $csv_rows){
$termWords = explode(" ", $csvdata[$y][0]);
$termWordCount = count($termWords);
$z = 0;
while($z <= $termWordCount){
if($terms[$x] != NULL){
if($termWords[$z] == $terms[$x]){
$sortedData[$terms[$x]][0] += intval($csvdata[$y][1]);
$sortedData[$terms[$x]][1] += floatval($csvdata[$y][2]);
$sortedData[$terms[$x]][2] += floatval($csvdata[$y][3]);value
$sortedData[$terms[$x]][3] += floatval($csvdata[$y][4]);
}
}
$z++;
}
$y++;
}
$x++;
}
return $sortedData;
}
【问题讨论】:
-
什么错误?内存分配错误?
-
另外,您的示例数据表明您在最后 4 列中有常规的 int 值,但您的代码尝试将它们转换为浮点数。
-
是的,我尝试在我的 php.ini 文件中同时增加 max_execution_time 和 memory_limit,但没有成功
-
最后三个是真实数据中的浮点数,只是上面的小例子中没有
-
作为一般优化,尝试一次读取 CSV 文件一条记录并以这种方式聚合数据(而不是将整个内容读入内存并循环访问)。