7

我试图确定一个 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);
?>

我敢肯定,这是我没有得到的那些简单易行的事情之一。

4

3 回答 3

16

如果我理解,您只需要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";
}
于 2011-10-06T17:38:58.250 回答
0

未经测试,但应该可以工作!

$allowedColNum=5;
$batchcount=0;
$file = fopen($file_name, "r"); 
$totCols=0;
while ($line = fgetcsv($file))
if(count($line) > $totCols) $totCols = count($line);
fseek($file, 0);
while ($line = fgetcsv($file))
{
  //....
}
fclose($file);

编辑:经过测试,工作 fseek(0) 而不是将值保存在数组中:会快很多

于 2011-10-06T17:45:51.333 回答
0

Michael Berkowski 的回答对我来说很好,但就我而言,我还必须在 fgetcsv() 函数调用中指定 csv 分隔符。它是逗号“,”,默认情况下,我将其更改为分号“;”。像这样:

而 ($line = fgetcsv($file, 0, ';')){

于 2015-08-12T16:04:04.907 回答