Jump to content

Generate different colors on table rows using array


rocky_88

Recommended Posts

I'm trying to set different colors on rows of a table using an array,

Problem is I cannot get it to work right, i'm not sure where to place my for loop so that it works right and generates a different color for different row.

$color = array(red,green,blue);
while ($row = mysql_fetch_assoc($exec))
{
echo '<tr>';
echo '<td>'.$row['brand_name'].'</td>';
echo '<td>'.$row['contact_name'].'</td>';
echo '<td>'.$row['contact_info'].'</td>';
echo '<td>'.$row['email'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '</tr>';
}

 

I tried putting for loop only for tr, but it didnt work.

for ($i=0;$i<=count($color);$i++)
{
echo "<tr bgcolor=\"".$color[$i]."\">";
}

 

I cannot put it within the while loop, it'll repeat the rows for all the colors.

So where exactly do I place the for loop so that it works right?

<?php
$color = array(red,green,blue);
$i=0;
while ($row = mysql_fetch_assoc($exec))
{
echo "<tr bgcolor=\"".$color[$i]."\">";
echo '<td>'.$row['brand_name'].'</td>';
echo '<td>'.$row['contact_name'].'</td>';
echo '<td>'.$row['contact_info'].'</td>';
echo '<td>'.$row['email'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '</tr>';
$i++;
if($i==count($color))$i=0;
}
?>

And, if you want to use some css that is not obsolete -

 

<?php

// list of colors (must be valid css color specifiers - name, HEX, RGB, ...)
$color = array('red','green','blue');

// build tr css color classes (tr.c0, tr.c1, ...)
$styles = '';
foreach($color as $key => $value){
$styles .= "tr.c$key {background-color:$value;}\n";
}

$max_color = count($color) - 1;
// build table content
$content = "<table>\n";
$i = 0;
while ($row = mysql_fetch_assoc($exec)){
$content .= "<tr class='c$i'>";
$content .= '<td>'.$row['brand_name'].'</td>';
$content .= '<td>'.$row['contact_name'].'</td>';
$content .= '<td>'.$row['contact_info'].'</td>';
$content .= '<td>'.$row['email'].'</td>';
$content .= '<td>'.$row['description'].'</td>';
$content .= "</tr>\n";
$i++;
if($i > $max_color){
	$i = 0;
}
}
$content .= "</table>\n";
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Cycle between table row colors</title>
<style type="text/css">
table {border-collapse:collapse;}
<?php echo $styles; ?>
</style>
</head>
<body>
<?php echo $content; ?>
</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.