Search code examples
phparraysnumericalleaderboard

php: Reordering an array and its subkeys


i am basically trying to make a leaderboard system. I need to put 2 types of data in my .yml file: the name of the player, and their score.

Here is a var dump:

array(3) {
  [0]=>
      array(2) {
        [0]=>
           string(10) "samueljh1_"
             [1]=>
                 int(3)
      }
      [1]=>
      array(2) {
        [0]=>
           string(12) "samueljh1_54"
             [1]=>
                 int(1)
      }
      [2]=>
      array(2) {
        [0]=>
           string(11) "samueljh1_1"
             [1]=>
                 int(8)
}

So, what I want to do is order this array, so that is is in numerical order - where the integers are.

Basically, converting the var dump above, to something like this:

array(3) {
  [0]=>
      array(2) {
        [0]=>
           string(11) "samueljh1_1"
             [1]=>
                 int(8)
      }
      array(2) {
        [1]=>
           string(10) "samueljh1_"
             [1]=>
                 int(3)
      }
      [2]=>
      array(2) {
        [0]=>
           string(12) "samueljh1_54"
             [1]=>
                 int(1)
      }

}

If this isn't possible, are there any alternate ways to store this data?

Thanks A lot, - Sam.


Solution

  • First, I suggest using the player name as an associative key for the score value and simplifying the structure of the array, like so:

    $testArray = array("samueljh1_" => 3, "samueljh1_54" => 1, "samueljh1_1" => 8);
    

    This makes the array much simpler to parse and makes the data structure more closely resemble the relationship between the data you have. Then the function arsort(), which does reverse sorting, is what you're looking for:

    arsort($testArray, SORT_NUMERIC); // $testArray is passed by reference
    
    var_dump($testArray);
    

    Yields

    array(3) {
      ["samueljh1_1"]=>
      int(8)
      ["samueljh1_"]=>
      int(3)
      ["samueljh1_54"]=>
      int(1)
    }