dsfs23434 2015-04-10 13:06
浏览 24
已采纳

php:重新排序数组及其子键[重复]

This question already has an answer here:

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.

</div>
  • 写回答

1条回答 默认 最新

  • duanmu6231 2015-04-10 13:17
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?