PHP 只递增一次
下面代码中 $i 的值始终为 2。看起来它会增加到第一次,但只是那一次。有什么想法吗?
foreach ($records as $row){
$i = 1;
$i++
if ($i % 2 != 0){
$trClass = 'odd';
}else{
$trClass = 'even';
}
echo '<tr class="' . $trClass . '"><td>' .
anchor("admin/delete/$row->id", 'delete') . '</td><td>' .
anchor("admin/edit/$row->id", 'Edit') . '</td>';
foreach ($row as $key => $value){
echo '<td>' . $value . '</td>';
}
echo '</tr>';
$i++;
}
The value for $i in the code below is always 2. It seems it increments to the first time, but only that time. Any thoughts?
foreach ($records as $row){
$i = 1;
$i++
if ($i % 2 != 0){
$trClass = 'odd';
}else{
$trClass = 'even';
}
echo '<tr class="' . $trClass . '"><td>' .
anchor("admin/delete/$row->id", 'delete') . '</td><td>' .
anchor("admin/edit/$row->id", 'Edit') . '</td>';
foreach ($row as $key => $value){
echo '<td>' . $value . '</td>';
}
echo '</tr>';
$i++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每次循环时,您都会将其重新分配给
1
。而是在循环外对其进行初始化。我还看到您在循环开始和结束时都在递增。我假设您只想执行一次(可能只保留最后的那个;删除开头的那个)。
You're reassigning it to
1
every time through the loop. Initialize it outside the loop instead.Also I see that you're incrementing both at the beginning of the loop and at the end. I assume you only want to do it once (probably keep only the one at the end; remove the one at the beginning).
您的代码存在逻辑错误,因为它在循环的每次迭代中都声明了 $i 。
这就是您要做的:
在每次迭代中声明 $i = 1,然后递增 $i。
所以在每次迭代中,你总是得到 $i = 2 。
在 foreach 循环之外声明 $i = 1 并仅增加 $i 一次,如下所示:
Your code has a logical error in that it declares $i in every iteration of the loop.
This is what you do:
declare $i = 1 in every iteration and then increment that $i.
so in every iteration, you get $i = 2 all the time.
declare $i = 1 outside the foreach loop and increment $i just once like so:
这样开始
start it this way
请在
foreach
之前添加$i = 1;
please put
$i = 1;
beforeforeach