问题
Hey guys, 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);
?>
回答1:
You have a typo in your if
condition. It should be:
if($i%2 == 0)
You can also save a few keystrokes by just assigning the class name to a variable in the if and else blocks:
if($i%2 == 0)
{
$class = 'even';
}
else
{
$class = 'odd';
}
echo "<tr class='$class'>";
echo "<td>" . $row['departure'] ." ✈ ". $row['destination'] . "</td>";
echo "</tr>";
回答2:
you can also use the css .nth-child property
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
As per W3 example
回答3:
CSS-Tricks has posted a very very elegant solution to this problem. It appears like super-reductionist C++ magic. Essentially they do this:
<div class="example-class<?php echo ($xyz++%2); ?>">
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
回答4:
You forgot a '$'
if(i%2 == 0)
Should be
if(($i % 2) == 0)
回答5:
Replace this line...
if(i%2 == 0)
...with the following:
if($i % 2 == 0)
回答6:
This can be improved further.
foreach($post_array as $array => $row) {
$class = ($array %2 == 0) ? 'even' : 'odd';
echo '
<tr class="'.$class.'">
<td>' .$row['title']. '</td>
<td>' .$row['content']. '</td>
<td>' .$row['catid']. '</td>
<td>' .$row['id']. '</td>
<td>' . '<form action="edit.php?id='.$row['id'].'" method="post">
<input type="hidden" name="id" id="id" value="'.$row['id'].'" />
<input type="submit" name="edit" value="Edit" />
</form>' . '</td>
<td>' . '<form action="" method="post">
<input type="hidden" name="id" id="id" value="'.$row['id'].'" />
<input type="submit" name="delete" value="Delete" />
</form>' . '</td>
</tr>';
}
来源:https://stackoverflow.com/questions/6112624/alternating-between-even-and-odd-in-a-while-loop-in-php