how to sort a multidemensional array by an inner key

后端 未结 6 1034
你的背包
你的背包 2020-12-02 02:34

i have this enormous array that i am pulling from an API for BattleField Bad Company 2, and the soldier stats can be pulled as a multi dimensional array with an inner array

相关标签:
6条回答
  • 2020-12-02 02:51

    In addition to the other answers, if you need to sort by a dynamic field (only known at runtime), you can use an anonymous function and pass it the field via the use keyword:

    $field = "some_dynamic_value";
    
    usort($rows, function($a, $b) use ($field) {
        return strcmp($a[$field], $b[$field]);
    });
    
    0 讨论(0)
  • 2020-12-02 02:57

    You can use array_multisort for this: first provide the column you want to sort -- with array_column and as second argument the whole array. There are several options possible (see documentation), but for an ascending sort by the "rank" field, it would look like this:

    array_multisort(array_column($players, "rank"), $players);
    

    NB: For the data in the actual question here, $players would be &$arr["players"]

    0 讨论(0)
  • 2020-12-02 03:05

    You can sort any array by any criteria using usort()

    0 讨论(0)
  • 2020-12-02 03:07

    To order descending an array, I used

    function sorterdesc($one, $two) {
        return ($two['cont'] - $one['cont']);
    }
    

    For ascending :

    function sorterasc($one, $two) {
        return ($one['cont'] - $two['cont']);
    }
    

    Like this it works fine with numeric values

    0 讨论(0)
  • 2020-12-02 03:09

    Here you go.

    $playergoop is the array that you provided.

    This one sorts by the sub-field 'rank', but it does so in an ascending order. If you want a descending order, you can switch the > to <.

    function sorter($one, $two) {
        return ($one['rank'] > $two['rank']);
    }
    
    usort($playergoop['players'], sorter);
    
    0 讨论(0)
  • 2020-12-02 03:10

    When you're using PHP 5.3 and above you can use an anonymous inline function for sorting:

    usort($obj, function ($a, $b)
    {
        return strcmp($a["name"], $b["name"]);
    });
    
    0 讨论(0)
提交回复
热议问题