
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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', ), )
- Related Articles
- Sort php multidimensional array by sub-value in PHP
- PHP Multidimensional Array.
- How do I sort a multidimensional array by one of the fields of the inner array in PHP?
- Sort LinkedHashMap by Keys in Java
- Sort an array of objects by multiple properties in JavaScript
- How to convert Multidimensional PHP array to JavaScript array?
- Multidimensional arrays in PHP
- Java Program to Sort map by keys
- C++ Program to Sort Dictionary by keys
- Swift Program to Sort Dictionary by keys
- Sort object array based on another array of keys - JavaScript
- Reset keys of array elements using PHP ?
- Return an array with numeric keys PHP?
- How to sort a dictionary in Python by keys?
- Sort LinkedHashMap by Keys using Comparable Interface in Java

Advertisements