PHP中的while循环在偶数和奇数之间交替
我一直在编写几行代码,但似乎无法让它工作。基本上我想通过 while 循环在偶数和奇数表格样式之间交替。我做错了什么?
似乎每次都只循环 if() 。
谢谢!
<?php
include 'connect.php';
echo "<table id='hor-zebra'>";
$i = 0;
while($row = mysql_fetch_array($result))
{
if(i%2 == 0)
{
echo "<tr class='even'>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
}
$i++;
}
echo "</table>";
mysql_close($con);
?>
I have been working on couple of lines of code but I can't seem to get it to work. Basically I want to alternate between even and odd table-styles via a while loop. What am I doing wrong?
Seems as though it only loops through the if() everytime.
Thanx!
<?php
include 'connect.php';
echo "<table id='hor-zebra'>";
$i = 0;
while($row = mysql_fetch_array($result))
{
if(i%2 == 0)
{
echo "<tr class='even'>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
}
$i++;
}
echo "</table>";
mysql_close($con);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的
if
条件中有拼写错误。它应该是:您还可以通过将类名分配给 if 和 else 块中的变量来节省一些击键:
You have a typo in your
if
condition. It should be:You can also save a few keystrokes by just assigning the class name to a variable in the if and else blocks:
您还可以使用 css .nth-child 属性
按照 W3 示例
you can also use the css .nth-child property
As per W3 example
CSS-Tricks 针对这个问题发布了一个非常非常优雅的解决方案。
它看起来就像超级还原论的 C++ 魔法。本质上他们是这样做的:
这适用于任何循环:for、foreach 和 while。
修改整数可以提供更大的步长,即在 3 后重置,在 4 后重置,依此类推。
CSS-Tricks 最终解决方案
CSS-Tricks has posted a very very elegant solution to this problem.
It appears like super-reductionist C++ magic. Essentially they do this:
This works in any loop: for, foreach and while.
Modifying the integer gives you larger step sizes, i.e. reset after 3, reset after 4 and so on.
CSS-Tricks final solution
你忘记了一个 '$'
应该是
You forgot a '$'
Should be
将此行...
...替换为以下内容:
Replace this line...
...with the following:
这可以进一步改进。
This can be improved further.