Free 20-minute strategy call with a senior engineer: AI, payments, eLearning or custom software
Engineering

Sort multidimensional arrays by multiple keys – PHP

Sort multidimensional arrays by multiple keys – PHP

In short

How to sort a multidimensional array by multiple keys in PHP using usort and array_multisort, with code examples.

We would like to share PHP Solution for sorting of multidimensional array with Multiple Keys. As developers, it’s likely that you encountered this situation where you have a list of items in the database that are fetched in a specific order but you want to display them in the front-end sorted by a value of that item.

Input Array :

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

Sorting Logic using array_mulitsort :

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

Final Output of $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',
  ),
)

Vibidsoft has expertise to solve this kind of Custom Programming problems and expert in custom application development.For more information mail us on [email protected].

Vibidsoft Engineering Team

Senior engineers who have shipped 450+ projects since 2014 across AI, payments, eCommerce, eLearning and custom software. Every guide is written and reviewed by the people who do the work.

Follow us on LinkedIn · About Vibidsoft

Next step

Talk to an engineer about Modernize & Rescue

Fixed-price upgrades for ageing PHP, Drupal, Magento or hybrid apps, with security patching and a care plan. from $5,000.

  • A 20-minute call with a senior engineer, not a salesperson
  • A written next-step plan within one business day
  • NDA on request
Book a call WhatsApp