Page 1 of 1

for loop + groupings

Posted: Sat May 08, 2010 6:57 pm
by worked
Hi there- Question for you. I have a simple for loop that writes table data to a web page. What I would like to do is group some of the data by similarity and alter the background color for each group. For visual instance:

2010
2010
2010

2009
2009

2008
2008
2008


I'm wondering if I need to push each group into an array, and then change the color of the even numbered indices. How might I push those groups into an array? Thanks any help is appreciated!

Code: Select all

for($i=0;$i<$total;$i++)
{
  $row = mysql_fetch_object($result);
  $year=$row->db_year;
  <table>
    <tr>
      <td <? if($year == $year)
      echo 'bgcolor = "#cccccc"'; ?>>
      <?= $year == "" ? "&nbsp" : $year; ?>
      </td>
    </tr>
  </table>
}

Re: for loop + groupings

Posted: Sat May 08, 2010 9:20 pm
by califdon
Each fetch is from an array, to begin with, so there's no reason to create another one. The details depend on whether you want specific colors for specific groups or whether you just want to alternate colors to highlight the changes, for which what you have is almost enough. However, I would advise against using "short tags" in PHP. It isn't portable to all servers. Always use <?php and echo.

Re: for loop + groupings

Posted: Sat May 08, 2010 11:55 pm
by worked
Thanks for the quick reply! So displaying an alternative color to highlight the changes is all that is necessary. In other words, every other group can be the same color. How might I do that? Any additional help is appreciated. Thanks!

Re: for loop + groupings

Posted: Sun May 09, 2010 12:18 pm
by califdon
Try this:

Code: Select all

<?php
$color=Array("#9999ff","#ff9999");
$prevclr=0;
$prevyr="";

echo "<table>";

while($row=mysql_fetch_object($result)) {
   $year=$row->db_year;
   if($year!=$prevyr) {
      $prevclr==0 ? 1 : 0;
   }
   echo "<tr><td style='color:".$color[$prevclr].">";
   echo "$year</td></tr>";
   $prevyr=$year;
}
 echo "</table>";
?>

Re: for loop + groupings

Posted: Sun May 09, 2010 8:21 pm
by worked
You are truly the man! Thanks brotha!