我正在尝试将上传的CSV文件处理成PHP中的数组。我有这个工作正常,但用户的一些文件最终有一堆空白行与分隔符。这通常发生在他们在现有文件上使用Excel时。突出显示旧细胞并清除它们。
示例CSV文件
lineNo,date,vendor,amount 1,5/2/2012,V000236,3727.21 2,5/2/2012,V003432,4826.19 ,,, ,,,
成为以下数组
Array ( [0] => Array ( [0] => lineNo [1] => date [2] => vendor [3] => amount ) [1] => Array ( [0] => 1 [1] => 5/2/2012 [2] => V000236 [3] => 3727.21 ) [2] => Array ( [0] => 2 [1] => 5/2/2012 [2] => V003432 [3] => 4826.19 ) [3] => Array ( [0] => [1] => [2] => [3] => ) [4] => Array ( [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;
}
最终,我希望这个回归
Array ( [0] => Array ( [0] => lineNo [1] => date [2] => vendor [3] => amount ) [1] => Array ( [0] => 1 [1] => 5/2/2012 [2] => V000236 [3] => 3727.21 ) [2] => Array ( [0] => 2 [1] => 5/2/2012 [2] => V003432 [3] => 4826.19 ) )
答案 0 :(得分:1)
一旦找到空值,你不能break;
你的while循环吗?
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
// ## Flag variable ##########
$empty = true;
for ($x = 0; $x < $c; $x++) { //Populate the array
// ## Test each value ##########
$empty = $empty && (empty($csvData[$x]));
if ($specialChars === TRUE) {
$arrayCSV[$csvKey][$x] = htmlspecialchars($csvData[$x]);
} else {
$arrayCSV[$csvKey][$x] = $csvData[$x];
}
}
// ## Stop loop if all empty ##########
if ($empty) {
unset($arrayCSV[$csvKey]);
break;
}
$csvKey++;
}
fclose($csvHandle);
}
答案 1 :(得分:1)
注意:
CSV文件中的空白行将作为包含单个 null 字段的数组返回,并且不会被视为错误。
if ($c == 1 && current($csvData) === null) {
break;
}
答案 2 :(得分:0)
您可以运行一个额外的循环以检查是否为空
Navigation Bar
答案 3 :(得分:-3)
我推荐这个完全符合你想要的php功能