November 3, 2011
alternating row colors
Question by meandme
I am looking for a solution to use the alternating colors row design in my table which is from a csv.
my code:
<?php
echo "<table style='text-align: left; width: 99%;' border='1'>nn
<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>";
?>
so how can i have the tr class to alternate from odds and even?
thanks
Answer by OptimusCrime
<?php
echo "<table style='text-align: left; width: 99%;' border='1'>nn
<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>";
?>
Or you could assign a class just the same way and style it using css. This is much better practice.
Answer by Starx
I will give you a better but much simpler solution, through CSS. First of all uniquely identify your table, i will show you a more general option.
table tr { backgroun: #ddd; }
table tr:nth-child(2n) { background: #ccc; }