Foreach内部的For循环 [英] For loop inside Foreach
问题描述
我有一个foreach,它为每个用户遍历数据库.
I got a foreach which loops through my database for each user.
<?php
foreach($users as $user) {
?>
<tr>
<td>
<?php
for ($i=1; $i < 52; $i++) {
echo $i;
}
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
此循环遍历数据库并回显用户名,现在我尝试在其中建立一个for循环,以便每个用户都有一个数字,我以一个非常基本的for循环为例(稍后将对其进行更改). 问题是我为每个用户打印了所有号码,但是我只想为一个用户打印一次号码.我该怎么解决.
This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later). The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.
推荐答案
如果要为用户提供唯一的索引号,则不需要多余的循环.
If you want unique index number for user, you do not need extra loop.
只需添加一个增量变量:
Just add an increment variable:
并在现有循环中将其递增.
And increment it in existing loop.
<?php
$i=0;
foreach($users as $user) {
++$i; // For printing first user, it will be 1 not 0.
// Therefore, increment is placed before printing name.
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php
}
?>
这篇关于Foreach内部的For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!