在 PHP 中按多个键对多维数组进行排序
array_multisort 函数可用于基于多个键对一个多维数组进行排序 −
示例
$my_list = array( array('ID' => 1, 'title' => 'data one', 'event_type' => 'one'), array('ID' => 2, 'title' => 'data two', 'event_type' => 'zero'), array('ID' => 3, 'title' => 'data three', 'event_type' => 'one'), array('ID' => 4, 'title' => 'data four', 'event_type' => 'zero') ); # The list of sorted columns and their data can be obtained. This will be passed to the array_multisort function. $sort = array(); foreach($my_list as $k=>$v) { $sort['title'][$k] = $v['title']; $sort['event_type'][$k] = $v['event_type']; } # It is sorted by event_type in descending order and the title is sorted in ascending order. array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$my_list);
对于 PHP 版本 5.5.0 −
array_multisort(array_column($my_list, 'event_type'), SORT_DESC, array_column($my_list, 'title'), SORT_ASC, $my_list);
输出
结果将是下面的输出 −
array ( 0 => array ( 'ID' => 4, 'title' => 'data four', 'event_type' => 'zero', ), 1 => array ( 'ID' => 3, 'title' => 'data two', 'event_type' => 'zero', ), 2 => array ( 'ID' => 1, 'title' => 'data one', 'event_type' => 'one', ), 3 => array ( 'ID' => 2, 'title' => 'data three', 'event_type' => 'one', ), )
广告