Sort multidimensional array by multiple keys in PHP


The array_multisort function can be used to sort a multidimensional array based on multiple keys −

Example

$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);

For PHP version 5.5.0 −

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

Output

This will produce the following output −

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

Updated on: 06-Apr-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements