bartibus Posted March 31, 2006 Share Posted March 31, 2006 Hi,Does anyone know how I can make a rank list from a series of numbers? I have a competition in which participants can gather points; in a mysql database table there's a row for each participant (users) and a column in which the point totals are saved (totals). When I use 'ORDER BY' to sort the users according to their totals, the rank is consecutive, even when two or more users have the same amount of points. Is it possible to make a script that sorts the users according to their totals and assigns a rank number, that remains the same if two or more users have the same total (and skips the relevant rank numbers)? Below is an example of what I would like to have:1 User A 2002 User B 1503 User C 1253 User D 1253 User E 1256 User F 100I hope that someone can help me with this,Thanks in advance,Bart Quote Link to comment Share on other sites More sharing options...
Barand Posted March 31, 2006 Share Posted March 31, 2006 try[code]<?php$scores = array ( 'User A' => 200, 'User B' => 150, 'User C' => 125, 'User D' => 125, 'User E' => 125, 'User F' => 100);$rank = 1;$prev = 0;$count = 0;foreach ($scores as $name => $score) { if ($score==$prev) { ++$count; } else { $rank = ++$count; } echo "$rank $name $score<br/>"; $prev = $score;}?>[/code] Quote Link to comment Share on other sites More sharing options...
bartibus Posted April 3, 2006 Author Share Posted April 3, 2006 Thanks,The problem is though that the scores are variable; the user A, etc. was just an example. I have tried to change the code so that it will retrieve the users and scores from the database, but the resulting list gives every user the same rank. This is my code:<? $query = "SELECT username, name, totaal FROM punten ORDER BY totaal DESC, name ASC"; $result = mysql_query($query) or die(mysql_error());while ($row = mysql_fetch_assoc ($result)) {$username= $row['username'];$name= $row['name'];$totaal= $row['totaal'];$scores = array($name => $totaal);$rank = 1;$prev = 0;$count = 0;foreach ($scores as $name => $totaal) { if ($totaal==$prev) { ++$count; } else { $rank = ++$count; } echo "$rank $name $totaal<br />"; $prev = $totaal;}}?>Do you know what is wrong with my code? Quote Link to comment Share on other sites More sharing options...
Barand Posted April 3, 2006 Share Posted April 3, 2006 If you are doing it straight from the db table, sorted, you can drop the array code.[code]$rank = 1;$prev = 0;$count = 0;while ($row = mysql_fetch_assoc ($result)) { $username= $row['username']; $name= $row['name']; $totaal= $row['totaal']; if ($totaal==$prev) { ++$count; } else { $rank = ++$count; } echo "$rank $name $totaal<br />"; $prev = $totaal;}[/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.