PHP 在 while 循环中 echo 问题
我使用 while 循环读取 csv 文件:
while (($data = fgetcsv($handle, null, ",")) !== FALSE)
并且我想跳过第一行,因为这是标题行,我想在屏幕上显示“跳过第一行”。
if($data[0]=="title")
echo "Title row..skipping<br />";
else
//do stuff
问题是因为它在一个 while 循环中,所以它多次打印出“标题行...跳过”,如下所示:
Checking row 0...
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Checking row 1...
我应该做什么,这样它只打印一次?这和php的输出缓冲有什么关系吗?
I read in a csv file by using a while loop:
while (($data = fgetcsv($handle, null, ",")) !== FALSE)
and i want to skip the first row because this is the title row and i want to display on the screen "first line skipped".
if($data[0]=="title")
echo "Title row..skipping<br />";
else
//do stuff
The problem is since its in a while loop it prints out "Title row...skipping" a bunch of times shown here:
Checking row 0...
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Title row..skipping
Checking row 1...
what should i do so it only prints it out once? does it have something to do with php's output buffering?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者在不进行赋值的情况下调用一次
fgetcsv($handle, null, ",")
,将处理程序向前移动一行:Or call
fgetcsv($handle, null, ",")
once without assignment, to move the handler forward by one line:如果您确定只需要跳过第一行;
If you know for a certain that you only need to skip the first line then;
我认为使用 foreach 会更优雅:
你现在的情况是,每次循环时都会检查
if (data[0] == "title")
。data[0]
将始终等于“title”,因此它的计算结果始终为 true。您可以增加$index
变量并在底部附近执行类似if (data[$index] == $title)
then$index++
的操作循环的一部分,但是当foreach
本质上会为你做这件事时,为什么要这样做呢?I think it'd be more elegant to use foreach:
How you have it now, you are checking
if (data[0] == "title")
every time you loop.data[0]
will always equal "title", so it will always evaluate to true. You could increment an$index
variable and do something likeif (data[$index] == $title)
then$index++
near the bottom of the loop, but why do that whenforeach
will essentially do that for you.