2011-11-03 144 views
2

我正在尋找一種解決方案,以使用來自csv的我的表中的交替顏色行設計。交替行顏色

我的代碼:

<?php 
echo "<table style='text-align: left; width: 99%;' border='1'>\n\n 
<thead> 
<tr> 
<th>data</th> 

</tr> 
</thead>"; 
$f = fopen("local/datafiles.csv", "r"); 
while (($line = fgetcsv($f)) !== false) { 
     echo "<tr class='odds'>"; 
     foreach ($line as $cell) { 
         echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>"; 
     } 
     echo "</tr>\n"; 
} 
fclose($f); 
echo "\n</table>"; 
?> 

所以,我怎麼能有TR類從賠率甚至交替? 感謝

+0

它與csv無關。 – onatm

回答

2
<?php 
echo "<table style='text-align: left; width: 99%;' border='1'>\n\n 
<thead> 
<tr> 
<th>data</th> 

</tr> 
</thead>"; 
$f = fopen("local/datafiles.csv", "r"); 
$i = 0; 
while (($line = fgetcsv($f)) !== false) { 
    echo "<tr style='background-color: ".(($i%2)?'green':'blue').";'>"; 
    foreach ($line as $cell) { 
     echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>"; 
    } 
    echo "</tr>\n"; 
    $i++; 
} 
fclose($f); 
echo "\n</table>"; 
?> 

適應,或者你可以分配一個類與使用css的方式和樣式相同。這是更好的做法。

+0

Thyks OptimusCrime這很明顯,我需要 – meandme

3

具有可變

詮釋計數= 0;在每次迭代

增量次數並採取modolous通過

計數%2

if(count % 2 == 0) 
color = red //(make color of row = red) 

else 
color = yellow //(make color of row = yello) 

count=count+1; 

那只是一個想法,美國可以在我們的代碼

2

你可以使用CSS僞選擇:第n-的類型(奇|偶)

http://reference.sitepoint.com/css/pseudoclass-nthoftype

如果表中的ID是styledTable,你的樣式看起來像:

#styledTable { 
text-align: left; 
width: 99%; 
border: 1px solid black; 
} 

#styledTable tr:nth-of-type(even) { 
background-color: red; 
} 

#styledTable tr:nth-of-type(odd) { 
background-color: blue; 
} 
2

我會給你一個更好,但更簡單的解決方案,通過CSS。首先唯一標識你的桌子,我會告訴你一個更普遍的選擇。

table tr { backgroun: #ddd; } 
table tr:nth-child(2n) { background: #ccc; } 
+0

我知道,這不是一個CSS問題,但它應該是 – Starx