PHP 中按多个键对数组进行排序

red*_*ted 0 php arrays sorting

我有一个表/数组。例如,在 Excel 中,我可以按第 1 列 asc、第 2 列 desc、第 3 列 asc 等排序。

我可以在 PHP 中做同样的事情吗?首先是["first_name"] ASC,然后["last_name"] DESC["player_id"] ASC["user_id"] DESC

array(2) {
    [0]=> array(6) {
        [0]=> string(8) "John",
        ["first_name"]=> string(8) "John",
        [1]=> int(7) "44",
        ["score"]=> int(7) "44",
        [2]=> string(2) "7",
        ["player_id"]=> string(2) "7",
        [3]=> string(2) "3",
        ["user_id"]=> string(2) "3"
    },
    [1]=> array(6) {
        [0]=> string(5) "Sam",
        ["first_name"]=> string(5) "Sam",
        [1]=> int(7) "55",
        ["score"]=> int(7) "55",
        [2]=> string(2) "1",
        ["player_id"]=> string(2) "1",
        [3]=> string(2) "6",
        ["user_id"]=> string(2) "61"
    }
}
Run Code Online (Sandbox Code Playgroud)

(实际上数组更长更深,这只是一个例子。)

更新:

function byPlayerID($player, $compare) {
    if($player['player_id'] > $compare['player_id'])
        return 1; // move up
    else if($player['player_id'] < $compare['player_id'])
        return -1; // move down
    else
        return 0; // do nothing

    if($player['score'] > $compare['score'])
        return 1; // move up
    else if($player['score'] < $compare['score'])
        return -1; // move down
    else
        return 0; // do nothing
}
Run Code Online (Sandbox Code Playgroud)

更新2:没关系,我只需要删除return 0;

Tuf*_*rım 5

array_multisort是您正在寻找的函数。

这是使用 array_multisort 编写的示例函数

https://gist.github.com/1220785

使用

   $sorted_arraty = sort_array_multidim($array,"first_name ASC, last_name DESC, player_id ASC, user_id DESC");
Run Code Online (Sandbox Code Playgroud)