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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog