我正在尝试确定csv文件有多少列.
这是我的脚本,它只使用了第一列,但我的运行略显失明.我想放置一个限制列数的变量.(因为我可能会犯一个错误并添加一列,甚至错过一列)
<?php
$allowedColNum=5;
$batchcount=0;
$file = fopen($file_name, "r");
while ($line = fgetcsv($file)){
/* I want to stop the loop if the $allowedColNum is not correct */
$col = $line[0];
echo $batchcount++.". ".$col."\n";
}
fclose($file);
?>
Run Code Online (Sandbox Code Playgroud)
我敢肯定,这是我不会轻易做到的事情之一.
Mic*_*ski 14
如果我理解,你只需要count($line),因为fgetcsv()已经返回了一个代表CSV文件中一行的数组.count()因此,数组是源列的数量.
while ($line = fgetcsv($file)){
// count($line) is the number of columns
$numcols = count($line);
// Bail out of the loop if columns are incorrect
if ($numcols != $allowedColNum) {
break;
}
$col = $line[0];
echo $batchcount++.". ".$col."\n";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15292 次 |
| 最近记录: |