Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If what you are doing works, you don't necessarily have to change it. Good to get ideas though, good that you asked.</p> <p>Here is an approach requiring only one hit on the database. Also, limiting the number of records returned will buy speed, especially if you have lots of scores to pick the top 10 from.</p> <pre><code> &lt;?php $query = 'SELECT * FROM highScores ORDER BY score DESC limit 0, 101'; $highScores = mysql_query($query); $ranks = array(); $scores = array(); $score_to_nexts = array(); $i=1; while ($highScore = mysql_fetch_array($highScores) and $i&lt;102): $ranks[$i] = $i; $scores[$i] = $highScore['score']; if ($i !== 1): $score_to_nexts[$i-1] = strval($scores[$i-1] - $scores[$i]) endif; $i++; endwhile; $i=1; while ($i&lt;11): $rank = $ranks[$i]; $scores = $scores[$i]; $score_to_next = $score_to_nexts[$i]; $i++; endwhile; ?&gt; </code></pre> <p>php rips through arrays with blinding speed, so this definitely would be close to as fast as it can be done. There might be some logic for squeezing down the cycles, but since your arrays only have to handle 11 members, I'd run with this.</p> <p>A problem with the routine you have is scores can change between DB reads, so your numbers could not add up right. By running the scores off one DB read, everything is going to be in sync. </p> <p>Regarding time for DB reads, it used to be that running extra DB reads was a big no-no, but now-days, that doesn't matter nearly as much. The webserver will load parts of the DB into memory, making DB reads often as fast as php-only in-memory operations. Exception would be if you are running a lot of data or getting a ton of traffic and need to conserve resources.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload