drvlf9739 2015-09-25 07:58
浏览 101
已采纳

如何在使用fopen和fgetcsv函数的上下文中将while循环转换为foreach循环?

This is the standard code on php.net:

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>
";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />
";
        }
    }
    fclose($handle);
}
?>

Let's assume that test.csv has 3 rows with:

cell11,cell12,cell13
cell21,cell22,cell23
cell31,cell32,cell33

Is it possible to use a foreach loop instead of the while used here and still get the values inside test.csv, for further use?

The code above gives this result:

3 fields in line 1: 
cell11
cell12
cell13
3 fields in line 2: 
cell21
cell22
cell23
3 fields in line 3: 
cell31
cell32
cell33

This is what I have tried:

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
//    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//        $num = count($data);
//        echo "<p> $num fields in line $row: <br /></p>
";
//        $row++;
//        for ($c=0; $c < $num; $c++) {
//            echo $data[$c] . "<br />
";
//        }
//    }
    foreach(($data = fgetcsv($handle, 1000, ",")) as $field){
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>
";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />
";
        }
    }
    fclose($handle);
}
?>

And the result:

3 fields in line 1: 
cell11
cell12
cell13
3 fields in line 2: 
cell11
cell12
cell13
3 fields in line 3: 
cell11
cell12
cell13
  • 写回答

1条回答 默认 最新

  • drd99007 2015-09-25 09:10
    关注

    This:

    foreach(($data = fgetcsv($handle, 1000, ",")) as $field){ ...
    

    Passes the data from fgetcsv to the new variable $data which doesn't make sense in this case. You can just write this:

    foreach (fgetcsv($handle, 1000, ",") as $field) { …
    

    But to explain why foreach doesn't work:

    As fget (and thus fgetcsv) is a function it does not work as an array, it just returns one, namely the next line in the file.

    The foreach example above just gets the first line from that function and iterates over it. This means you iterate over each column of the first line.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?