PDA

View Full Version : PHP Problem with Ranking code



selliott
January 20th, 2009, 03:37 AM
I need help fine tuning my code. This code shows ranking like:

Rank - Points
1 - 120
2 - 100
2 - 100
3 - 99

But I need it to show it like:

1 - 120
2 - 100
2 - 100
4 - 99

**Notice the 4th result is ranked 4th instead of 3rd...since the two tied for 2nd are actually 2nd and 3rd.



<?php

echo '<table cellpadding="3" cellspacing="0" style="width:100%;">
<tr>
<td>Rank</td><td>User</td><td>Points</td>
</tr>';
$rank = 0;

while($row = mysql_fetch_array($Points)){

$score = $row['Points'];

$r = ($score == $oldScore)? $rank : ++$rank;
echo '

<tr>
<td class="topline">' . $r . '</td>
<td class="topline">' . $row['Name'] . '</td>
<td class="topline">' . $score . '</td>
</tr>';

$oldScore = $score;
}
echo '</table>';

?>

borrob
January 20th, 2009, 07:21 AM
something like:
$counter = 0;

while($row = mysql_fetch_array($Points))
{
$counter++;
$score = $row['Points'];
if( $score != $oldScore )
{
$rank = $counter;
echo '

<tr>
<td class="topline">' . $rank . '</td>
<td class="topline">' . $row['Name'] . '</td>
<td class="topline">' . $score . '</td>
</tr>';
}
$oldScore = $score;
}

selliott
January 23rd, 2009, 02:39 AM
Thanks for the reply. Your code caused only the first person in the tie rank to show up (hid the others), but seeing your example showed me your idea about using a counter to track the # of times there was a tie. :) I was able to apply that idea to my code and now it's working perfectly! THANKS!!

eyebum
January 25th, 2009, 11:06 PM
Hey Selliot-


Thanks for the reply. Your code caused only the first person in the tie rank to show up (hid the others), but seeing your example showed me your idea about using a counter to track the # of times there was a tie. :) I was able to apply that idea to my code and now it's working perfectly! THANKS!!

any chance you could put that code up here for others to see?
Thanks!

eyebum

eyebum
January 27th, 2009, 03:04 AM
never mind, selliot...
I figured it out. Here's my version of how to correctly handle ties in a ranking system:


//mysql stuff like headers and the initial query and such...
$counter = 1;
$lastScore = 1;
$rank=1;
$lastrank=1;
while($row = mysql_fetch_array($result)){

if ($lastScore != $row['Total']) {
$rank=$counter;
}
elseif ($lastscore == $row['Total']){
$rank=$lastrank;
}

echo "<tr><b>";
echo '<td><span class="table_text_blue_italic_12pt"><b>'.$rank.'</span>
<td><span class="table_text_blue_italic_12pt"><b>'.$row['Handler'].'</span>
<td><span class="table_text_blue_italic_12pt"><b>'.$row['Dog'].'</span>
<td><span class="table_text_blue_italic_12pt"><b>'.$row['Total'].'</span></td>';
echo '</b></tr>';
$counter++;
$lastScore = $row['Total'];
$lastrank=$rank;
}

Posting this cuz I searched the entire universe for the correct code, and nobody, anywhere, had it. So here it is.