使用php循环进行简单分组?

I am outputting a table of rates. Each rate period has a Daily Rate and a Weekly rate, but the rate PERIODS remain the same.

So I am attempting to change the background color after ever TWO sets. So basically, the table will show:

Date 1 - Weekly Rate
Date 1 - Daily Rate
<change bg color>
Date 2 - Weekly Rate
Date 2 - Daily Rate
<change bg color back to original>

At the moment, I have two styles set up for background colors in my stylesheet. And the code i am using is giving me ALTERNATING rows. I just cannot see why it's changing every one, instead of every OTHER one!

To do this, I MUST compare one Date1 to Date2. ( I cannot make it change every two iterations, for reasons I do not want to go into.)

Here is my code so far inside the while loop. Help! And thank you.

if ($previous !== $row[datefrom])
{       
    $thecolor = "bg1";
} 
else 
{
    $thecolor = "bg2";
}

echo "<tr class=\"".$thecolor."\"> 
";
echo "<td>" .  $row[datefrom] . " - " . $row[dateto]. "</td> 
";
echo "<td>" .  str_replace(" 3-5","",$row[Ratetype]) . "</td> 
";
echo "<td>$" .  $row[Rate] . "</td> 
";
echo "</tr> 
";

$previous = $row[datefrom];

You also have to remember last used background color, without it background will change only for first entry in group. Example:

$use_original_bg = TRUE;

for(/*...*/){
    if ($previous !== $row[datefrom]) {
        $use_original_bg = !$use_original_bg; 
    }
    $thecolor = $use_original_bg?"bg1":"bg2";
}

We can see the reason for this very easy if we set up the states of current date and prev for each iteration:

 1. date1, prev = nothing => bg1
 2. date1, prev = date1   => bg2
 3. date2, prev = date1   => bg1
 4. date2, prev = date2   => bg2

One easy way to solve this problem is to also take into account the state of the background. I'll leave that up to you to give it some thinking.