doutu3352 2012-06-01 07:32
浏览 33
已采纳

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

I have a table/array. E.g. in Excel I can sort by column 1 asc, column 2 desc, column 3 asc, etc.

Can I do same in PHP? First with ["first_name"] ASC, then ["last_name"] DESC, ["player_id"] ASC and ["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"
    }
}

(The array is much longer and deeper in reality, this is just an example.)

Update:

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
}

Update 2: Never mind, I just needed to remove return 0;

  • 写回答

4条回答 默认 最新

  • dounaidu0204 2012-06-01 07:40
    关注

    Use usort().

    Example:

    $byPlayerID = function($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
    };
    
    usort($players, $byPlayerID);
    // now $players is sorted!
    

    This does require PHP 5.3 though, below is a more backwards compatible version

    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
    }
    
    usort($players, "byPlayerID");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?