循环查询结果集时维护计数器
我有以下问题:
$counter = 1;
while ($row = mysql_fetch_assoc($result)) {
$counter2 = $counter++;
echo $counter2 . $row['foo'];
}
是否有更简单的方法可以为每个结果获得 1,2,3 等,或者这是最好的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不需要 $counter2。 $counter++ 没问题。如果您使用前增量而不是后增量,您甚至可以在与 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.
我知道这并不完全是您所要求的 - 但您为什么不简单地使用 for 循环而不是 while 呢?
I know it's not exactly what you have asked for - but why don't you simply use a for-loop instead of while?
很长一段时间以来:
mysql
API 已经过时,mysqli
API 的结果集对象已经可以通过foreach()
进行遍历,就像一个数组一样关联行。无需手动维护计数器,只需访问
foreach()
提供的索引即可。代码:(演示)
For a long time:
mysql
API has been obsolete andmysqli
API's result set object has been traversable viaforeach()
as if an array of associative rows.Instead of maintaining the counter manually, just access the index that the
foreach()
provides.Code: (Demo)