Ranking Loop

I am trying to figure out how to assign a number rank to a set of results, but I need to reset the ranking when a certain column changes. For example:

Brand Rank
a 1
a 2
a 3
b 1
b 2
b 3

I set $rank=0; and then for each item in my loop I add $rank++; How do I get the rank to reset in the loop when the brand changes? Thanks for any help.

Where are you getting the brand from? If they were in an array, for example, then this would work:

[php]$items = array(‘a’, ‘a’, ‘a’, ‘b’, ‘b’, ‘b’);

// Reset the rank
$rank = 0;

// Set the last item for detecting a change
$last_item = $items[0];

// Loop through items
foreach($items as $item) {
// If the last item we looked is the same as this one, then increment rank
if($item == $last_item) {
$rank++;
} else {
// If it’s different, output the rank so far
echo 'Rank for item ', $last_item, ’ is ', $rank, ‘
’;

	// Change the last item
	$last_item = $item;
	
	// Reset the rank (1 as we've seen this once)
	$rank = 1;
}

}

echo 'Rank for item ', $last_item, ’ is ', $rank;[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service