Sort multidimensional array by multiple keys

前端 未结 7 777
挽巷
挽巷 2020-11-22 10:05

I\'m trying to sort a multidimensional array by multiple keys, and I have no idea where to start. I looked at uasort, but wasn\'t quite sure how to write a function for what

7条回答
  •  时光说笑
    2020-11-22 10:35

    You need 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);
    

    As of PHP 5.5.0:

    array_multisort(array_column($mylist, 'event_type'), SORT_DESC,
                    array_column($mylist, 'title'),      SORT_ASC,
                    $mylist);
    

    $mylist is now:

    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',
      ),
    )
    

提交回复
热议问题