Creating a leaderboards, how would I go about displaying rank/position?

丶灬走出姿态 提交于 2019-12-13 12:22:26

问题


I am creating a leaderboards which will display the following: Rank, Username, Score

I currently have the table to it will display Username and Score from the data in a mysql table, I am just wondering how would I go about displaying a rank for each user, number 1 being the user with the highest score then descending.

Thanks!


回答1:


I recommend reading up on PHP/MySQL.

HTML Header: Open your table, create your headers

<table>
    <tr>
        <td>Rank</td>
        <td>User</td>
        <td>Score</td>
    </tr>

PHP: Dynamically generate the rows for each user

    <?php

        $result = mysql_query("SELECT user, score FROM leaderboard ORDER BY score DESC");
        $rank = 1;

        if (mysql_num_rows($result)) {
            while ($row = mysql_fetch_assoc($result)) {
                echo "<td>{$rank}</td>
                      <td>{$row['user']}</td>
                      <td>{$row['score']}</td>";

                $rank++;
            }
        }
    ?>

HTML Footer: need to close the table

</table>



回答2:


You can do the whole thing in SQL:

SET @row = 0;
SELECT
    @row := @row + 1 AS rank
    userName,
    score
FROM
    leaderboard
ORDER BY
    score DESC



回答3:


You need to 1) get the score of the record you're trying to rank 2) count the number of records with a "better" score ("better" is dependent on your type of game. Basketball, higher scores are better. Golf, lower scores are better.)

So, something like

select records in order
for each record
    score = record.score
    rank = select count(*) + 1 from table where score_column is better than score
    display data
end for

The problem is that performing the count(*) on any significant amount of data is slow. But you can see that once you have the rank of the first TWO differing scores, you can determine the rank of the remaining rows in your code without a query. But remember: you probably need to account for ties.



来源:https://stackoverflow.com/questions/7096551/creating-a-leaderboards-how-would-i-go-about-displaying-rank-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!