我正在尝试将上传的 CSV 文件处理成 PHP 中的数组。我的工作正常,但是来自用户的一些文件最终有一堆带分隔符的空白行。这通常发生在他们在现有文件上使用 Excel 时。突出显示旧单元格并清除它们。
示例 CSV 文件
行号、日期、供应商、金额 1,5/2/2012,V000236,3727.21 2,5/2/2012,V003432,4826.19 ,,, ,,,
变成下面的数组
大批 ( [0] => 数组 ( [0] => 行号 [1] => 日期 [2] => 供应商 [3] => 数量 ) [1] => 数组 ( [0] => 1 [1] => 2012 年 5 月 2 日 [2] => V000236 [3] => 3727.21 ) [2] => 数组 ( [0] => 2 [1] => 2012 年 5 月 2 日 [2] => V003432 [3] => 4826.19 ) [3] => 数组 ( [0] => [1] => [2] => [3] => ) [4] => 数组 ( [0] => [1] => [2] => [3] => ) )
我不想只删除任何空白行,我想在数组索引 2 之后停止。在我的函数上放轻松我是新人:P
function csvToArray($csvFile, $specialChars = FALSE) {
$arrayCSV = array();
if (($csvHandle = fopen($csvFile, "r")) !== FALSE) { // Open the CSV
$csvKey = 0; // Set the parent array key to 0
while (($csvData = fgetcsv($csvHandle)) !== FALSE) {
$c = count($csvData); // Count the total keys in each row
//need something to stop on blank delimiter rows ,,,
for ($x = 0; $x < $c; $x++) { //Populate the array
if ($specialChars === TRUE) {
$arrayCSV[$csvKey][$x] = htmlspecialchars($csvData[$x]);
} else {
$arrayCSV[$csvKey][$x] = $csvData[$x];
}
}
$csvKey++;
}
fclose($csvHandle);
}
return $arrayCSV;
}
最终,我希望这个返回
大批 ( [0] => 数组 ( [0] => 行号 [1] => 日期 [2] => 供应商 [3] => 数量 ) [1] => 数组 ( [0] => 1 [1] => 2012 年 5 月 2 日 [2] => V000236 [3] => 3727.21 ) [2] => 数组 ( [0] => 2 [1] => 2012 年 5 月 2 日 [2] => V003432 [3] => 4826.19 ) )