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

2021-12-26 00:00:00 while-loop php

我有以下几点:

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

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

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

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

谢谢

推荐答案

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

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.

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

相关文章