【问题标题】:PHP fgetcsv() - find number of columnsPHP fgetcsv() - 查找列数
【发布时间】:2011-10-06 17:36:49
【问题描述】:

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

我确信这是我没有得到的那些简单易行的事情之一。

【问题讨论】:

    标签: php fgetcsv


    【解决方案1】:

    如果我理解,您只需要 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";
    }
    

    【讨论】:

    • 我明白了!我想我对在获取单个行之前和之后查找 $numcols 感到困惑。我想这不是它的工作方式,因为特定行的列号可能与同一文件中的其他行不同。但老实说,我是在做一个假设,因为我是文件新手。
    【解决方案2】:

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

    $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) 而不是将值保存在数组中:会快很多

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-20
        • 2021-06-13
        • 2016-08-22
        • 1970-01-01
        相关资源
        最近更新 更多