我有一个值数组,我使用 while 循环来查找每个值的 CSV 文件并列出所有匹配项
但是,由于某种原因, while 循环只执行第一个 foreach 循环 - 所有后续循环都什么都不退出 ---
foreach ($selectedpaths as $path) {
echo "<BR>working on this: " . $path . "<BR>";
#run through the csv
while ($row = fgetcsv($allroutes)) {
echo ".";
#fetch entries that match
if ($row[5] == $path) {
echo "<BR>" .$row[5] . " == " . $path ." MATCH " . $row . "<BR>";
}
}
}
这是该代码的输出:
working on this: test1
.....................................................................................
test1 == test1 MATCH A1,B1,C1,D1,E1,test1
........................................
test1 == test1 MATCH A6,B6,C6,D6,E1,test1
.......................................................................
test1 == test1 MATCH A68,B68,C68,D68,E1,test1
..............................................................................................................................................................................................................
working on this: test2
working on this: test3
working on this: test4
我可以从“working on this: X”中看到它肯定是依次循环每个查找
但即使它没有找到匹配项,它仍然应该输出点来表示它至少循环遍历 csv 来尝试......但它在第一个循环后不输出任何内容
如果它从未起作用我会理解,但为什么它第一次起作用? php 执行 while 循环的方式是不是有些奇怪?
文件指针第一次已经到达文件末尾,因此没有更多行可返回:
fgetcsv($allroutes)
大概在此之前的某个地方您调用了类似的方法来打开文件流:
$allroutes = fopen("some_file.csv", "r")
您可以将流倒回到文件的开头,然后再尝试再次循环:
rewind($allroutes);
// the while loop here
或者可能将整个文件打开操作移至
foreach
循环中:
$allroutes = fopen("some_file.csv", "r")
// the while loop here