php 从while循环中获取计数器的更简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6087364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:19:12  来源:igfitidea点击:

easier way to get counter from while loop?

phpwhile-loop

提问by Bob

I have the following:

我有以下几点:

$counter = 1;   
while($row= mysql_fetch_assoc($result)) {
    $counter2 = $counter++;

    echo($counter2 . $row['foo']);
}

Is there an easier way to get 1,2,3 etc for each result or is this the best way?

有没有更简单的方法可以为每个结果获得 1,2,3 等,或者这是最好的方法?

Thanks

谢谢

回答by GordonM

You don't need $counter2. $counter++ is fine. You can even do it on the same line as the echo if you use preincrement instead of postincrement.

你不需要 $counter2。$counter++ 很好。如果您使用 preincrement 而不是 postincrement,您甚至可以在与 echo 相同的行上执行此操作。

$counter = 0;   
while($row= mysql_fetch_assoc($result)) {
    echo(++$counter . $row['foo']);
}

回答by Daniel Freudenberger

I know it's not exactly what you have asked for - but why don't you simply use a for-loop instead of while?

我知道这不完全是你所要求的 - 但你为什么不简单地使用 for 循环而不是 while 呢?

for ($i = 0; $row = mysql_fetch_assoc($result); ++$i) {
    echo $i . $row['foo'];
}