for loop + groupings

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
worked
Forum Newbie
Posts: 6
Joined: Sat May 08, 2010 6:40 pm

for loop + groupings

Post 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>
}
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: for loop + groupings

Post 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.
worked
Forum Newbie
Posts: 6
Joined: Sat May 08, 2010 6:40 pm

Re: for loop + groupings

Post 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!
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: for loop + groupings

Post 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>";
?>
worked
Forum Newbie
Posts: 6
Joined: Sat May 08, 2010 6:40 pm

Re: for loop + groupings

Post by worked »

You are truly the man! Thanks brotha!
Post Reply