PHP问题使用fgetcsv然后foreach

时间:2012-09-07 00:47:05

标签: php foreach fgetcsv

好的,这就是事情。

if (!$fp=fopen($file,"r")) echo "The file could not be opened.<br/>";  
            while (( $data = fgetcsv ( $fp , 1000 , ',')) !== FALSE ) {
                // here, var_dump($data); shows the correct array
                $i = 0; 
                foreach ($data as $i=>$row ) {  
                   $matrix=explode( ',', $row);
                   // $matrix recieves only the first field of the csv line
                   // seems like I'm getting a field on each foreach iteration
                   // shouldn't I get the whole line each time?
                } //end foreach
            } //end while

我真的没有看到这里的问题。 顺便说一句,这段代码在我的本地机器上运行,并且在我的服务器上不起作用。两者都是linux,php版本是相同的。

有什么想法?谢谢。

1 个答案:

答案 0 :(得分:0)

fgetscv()将每一行作为数组返回。所以你的问题是:

$ data是一行,已经是一个数组。 while()循环中的每次迭代都将返回一行。没有必要爆炸。

$allRowsAsArray = array();
if (!$fp=fopen($file,"r")) echo "The file could not be opened.<br/>";  
while (( $data = fgetcsv ( $fp , 1000 , ',')) !== FALSE ) 
{
    $allRowsAsArray[] = $data;
}
print_r($allRowsAsArray); //Will return your entire csv as an array of rows, each row as an array.