1

I have implemented in my game an online score system via FTP. Here, take a look at the text file that gets updated :

User0:1000
User1:1500
User2:250
User3:700

Then, what I'd do is creating a table that has 3 columns : Rank | Name | Score

I was already able to extract the name and the score for each individual line :

<table><td>Rank</td><td>Name</td><td>Score</td>
<?php $lines = file("./scores/pk.txt");
for($i=0;$i<count($lines);$i++) {
    echo "<tr><td></td>";
        echo "<td>".substr($lines[$i],0,strpos($lines[$i],":"))."</td>";
        echo "<td>".substr($lines[$i],strpos($lines[$i],":")+1)."</td>";
    echo "</tr>";
} ?> </table<

But you know, if I execute this, I get the first column empty (because of the "<td></td>").

So my question is (finally) :

How to sort this array by third column and assigning the right rank in the first column ?

In my example it would look like :

Rank | Name  | Score

   1     | User1 | 1500

   2     | User0 | 1000

   3     | User3 | 700

   4     | User2 | 250

1
  • instead of <td></td> always use <td>&nbsp;</td> the non-breaking space will make the cell actually show Commented Aug 6, 2015 at 19:17

1 Answer 1

1

This should work for you:

Just loop through each line of your file with array_map() and explode() it by a colon.

Then you can simply sort it with usort(). And then you can display the data in your table.

<?php

    $lines = file("./scores/pk.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $lines = array_map(function($v){
        return explode(":", $v);
    }, $lines);

    usort($lines, function($a, $b){
        return $b[1] - $a[1];
    });

    echo "<table border='1'><tr><td>Rank</td><td>Name</td><td>Score</td></tr>";
        foreach($lines as $rank => $line)
            echo "<tr><td>" . ($rank+1) . "</td><td>" . $line[0] . "</td><td>" . $line[1] . "</td></tr>";
    echo "</table>";
?>

output:

Rank    Name    Score
 1     User1    1500
 2     User0    1000
 3     User3    700
 4     User2    250
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.