<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td>
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
如何为背景颜色制作图案?前,灰色,蓝色,灰色蓝色。while循环中的图案
<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td>
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
如何为背景颜色制作图案?前,灰色,蓝色,灰色蓝色。while循环中的图案
你需要的东西就像一个状态变量,您存储最后一排是蓝色还是灰色。然后,您打印出其他颜色并更新下一次传递的状态变量。
这是一个例子:
<?php
echo '<table>';
$state = 1;
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
if($state%2 == 0)
echo '<td style="background-color:grey;">';
else
echo '<td style="background-color:blue;">';
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
echo '</td></tr>';
$state++;
}
echo '</table>';
?>
有多种方法可以做到这一点。这是一个。
<table>
<?php $i = 0; ?>
<?php while ($row = mysql_fetch_assoc($result)): ?>
<tr<?php echo (++$i & 1 == 1) ? ' class="odd"' : '' ?>>
<td>
<?php echo $row['test'] . " " . ' ($' . $row['test2'] . ") ?><br>
</td>
</tr>
<?php endwhile; ?>
</table>
我建议给每个第二行一个CSS类(我称之为“奇数”),而不是奇数和偶数。那么你只需要:
tr td { background: grey; }
tr.odd td { background: blue; }
在CSS中。
如果它是2色图案,请使用变量在蓝色和灰色之间切换。如果超过2种颜色,使用旋转计数器
2种颜色
$blue = true;
<table>
while ($row = mysql_fetch_assoc($result)) {
<tr>
<td color="<?php echo $blue?'blue':'grey'; $blue ^= true; ?>">
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>";
</td>
</tr>
}
</table>
超过2种颜色,一般解决方法:
$colourIndex = 0;
$colours = ('blue', 'red', 'green');
...
...
<td color="<?php echo $colours[$colourIndex]; $colourIndex = ($colourIndex+1)%length($colours); ?>">
'$ blue =!$ blue'是一个较少的_clever_方法。 – 2009-10-25 08:08:24
什么是旋转计数器? – Strawberry 2009-10-25 08:08:32
($ counter + 1)%n其中n是您拥有的颜色数量:P – 2009-10-25 08:09:47
您还可以使用InfiniteIterator一次又一次地重复上述步骤。这就像“旋转柜台”一样,适用于任意数量的元素。
$props = new InfiniteIterator(
new ArrayIterator(array('a', 'b', 'c','d', 'e'))
); $props->rewind();
$l = rand(10, 20); // or whatever
for ($i=0; $i<$l; $i++) {
$p = $props->current(); $props->next();
echo 'class="', $p, '"... ';
}
这太复杂了! – 2009-10-25 08:52:43
真的吗?我发现这个解决方案比其他解决方案更容易阅读。而且更容易调整。 – chendral 2009-10-25 11:01:48
你的英语没有意义。颜色不要求你为他们制作图案。 – 2009-10-25 08:05:19
说什么才是正确的方法? – Strawberry 2009-10-25 08:07:13
@Doug:建议,“如何制作具有交替背景颜色的图案?” – Spoike 2009-10-25 08:14:04