tags:

views:

38

answers:

2

I am creating a table (stats_1) dynamically and would like to have each row of different background color. So far, all the lines have the same background color.

I have the following php code that prints echoes out and statements:

$keys = array('Col1', 'Col2','Col3','Col4','Col5','Col6','Col7');
echo '<table id="stats_1"><tr>';            
foreach ($keys as $column)
   echo '<th>' . $column . '</th>';
    echo '</tr>';

foreach ($data as $row){                        
   echo '<tr class="alt">';                     
     foreach ($keys as $column)
        if (isset($row[$column])){              
          echo '<td>' . $row[$column];
          } else {
          echo '<td>' . '' . '</td>';
        }
}
echo '</table>';

I need some help making EVERY OTHER ROW ($row) have a different COLOR, but don't know how to do that programmatically with the echo statement. So, it would alternate printing between:

echo '<tr class="alt">';  or   echo '<tr>';

I define that in a class:

#stats_1 tr.alt td
{
color:#000000;                  
background-color:#E0E0FF;       
}

THanks for your help/input.

+3  A: 

Try:

$counter = 0;
foreach ($data as $row){
  $counter++;

  $class = $counter % 2 === 0 ? 'foo' : 'bar';
  echo '<tr class="' . $class . '">';

  // more code....

Where foo and bar are supposed to be the class names of your alternate colors.

Sarfraz
@Sarfraz - Thank you! Works perfectly.
cjd143SD
@cjd143SD: You are welcome :)
Sarfraz
+1  A: 

CSS

http://www.w3.org/Style/Examples/007/evenodd - it cannot be done simply via CSS because support of nth-child property is not very good so far.

JavaScript

http://api.jquery.com/odd-selector/ - The task is quite easy with jQuery library in JavaScript. The disadvantage is that the colors may appear a little bit late and user may notice that (a disadvantage from MY perspective).

PHP

@Sarfraz presented a simple way how to accomplish the coloring with PHP.

Conclusion

PHP seems best bet until the CSS property nth-child is implemented in major browsers.

MartyIX
Thanks MartyIX for the alternatives and explanations to why this is difficult with CSS.
cjd143SD