2011-10-06 158 views
5

我試圖確定一個csv文件有多少列。PHP fgetcsv() - 查找列數

這是我的腳本,它只使用第一列,但我稍微失明。我想放置一個限制列數的變量。 (因爲我可能犯了一個錯誤,並添加一列,甚至錯過一列)

<?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); 
?> 

我敢肯定,這是我沒有得到的那些容易的事情之一。

回答

13

如果我明白了,您只需要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"; 
} 
+0

我明白了!我認爲自己在獲取單個行之前找到$ numcols之前感到困惑。我想這不是它的工作方式,因爲可能特定行的列號與同一文件中的其他列不同。但我真的在做一個假設,因爲我是新的文件。 – coffeemonitor

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),而不是保存在一個數組中的值:會快很多

0

邁克爾Berkowski答案的工作對我很好,但在我的情況,我還必須在fgetcsv()函數調用中指定csv分隔符。它是逗號「,」默認情況下,我將它改爲分號「;」。像這樣:

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