2009-10-25 79 views
0
<table> 
while ($row = mysql_fetch_assoc($result)) { 
<tr> 
<td> 
echo $row['test'] . " " . ' ($' . $row['test2'] . ")<br>"; 
</td> 
</tr> 
} 
</table> 

如何爲背景顏色製作圖案?前,灰色,藍色,灰色藍色。while循環中的圖案

+0

你的英語沒有意義。顏色不要求你爲他們製作圖案。 – 2009-10-25 08:05:19

+0

說什麼纔是正確的方法? – Strawberry 2009-10-25 08:07:13

+1

@Doug:建議,「如何製作具有交替背景顏色的圖案?」 – Spoike 2009-10-25 08:14:04

回答

1

你需要的東西就像一個狀態變量,您存儲最後一排是藍色還是灰色。然後,您打印出其他顏色並更新下一次傳遞的狀態變量。

這是一個例子:

<?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>'; 

?> 
2

有多種方法可以做到這一點。這是一個。

<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中。

1

如果它是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); ?>"> 
+0

'$ blue =!$ blue'是一個較少的_clever_方法。 – 2009-10-25 08:08:24

+0

什麼是旋轉計數器? – Strawberry 2009-10-25 08:08:32

+0

($ counter + 1)%n其中n是您擁有的顏色數量:P – 2009-10-25 08:09:47

0

您還可以使用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, '"... '; 
} 
+0

這太複雜了! – 2009-10-25 08:52:43

+0

真的嗎?我發現這個解決方案比其他解決方案更容易閱讀。而且更容易調整。 – chendral 2009-10-25 11:01:48