开发者社区> 问答> 正文

通过多个键对多维数组进行排序

我试图通过多个键对多维数组进行排序,但我不知道从哪里开始。我看了uasort,但不确定如何根据需要编写函数。

我需要按状态排序,然后按event_type排序,然后按日期排序。

我的数组如下所示:

Array

( [0] => Array ( [ID] => 1 [title] => Boring Meeting [date_start] => 2010-07-30 [time_start] => 06:45:PM [time_end] => [state] => new-york [event_type] => meeting )

[1] => Array
    (
        [ID] => 2
        [title] => Find My Stapler
        [date_start] => 2010-07-22
        [time_start] => 10:45:AM
        [time_end] => 
        [state] => new-york
        [event_type] => meeting
    )

[2] => Array
    (
        [ID] => 3
        [title] => Mario Party
        [date_start] => 2010-07-22
        [time_start] => 02:30:PM
        [time_end] => 07:15:PM
        [state] => new-york
        [event_type] => party
    )

[3] => Array
    (
        [ID] => 4
        [title] => Duct Tape Party
        [date_start] => 2010-07-28
        [time_start] => 01:00:PM
        [time_end] => 
        [state] => california
        [event_type] => party
    )

...... etc 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 19:22:34 408 0
1 条回答
写回答
取消 提交回答
  • 你需要 array_multisort

    $mylist = array( array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'), array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'), array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'), array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party') );

    get a list of sort columns and their data to pass to array_multisort

    $sort = array(); foreach($mylist as $k=>$v) { $sort['title'][$k] = $v['title']; $sort['event_type'][$k] = $v['event_type']; }

    sort by event_type desc and then title asc

    array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist); 从PHP 5.5.0开始:

    array_multisort(array_column($mylist, 'event_type'), SORT_DESC, array_column($mylist, 'title'), SORT_ASC, $mylist); $mylist 就是现在:

    array ( 0 => array ( 'ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party', ), 1 => array ( 'ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party', ), 2 => array ( 'ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting', ), 3 => array ( 'ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting', ), )

    2020-02-08 19:27:16
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载