Home >Backend Development >PHP Tutorial >How to Sort a Multidimensional Array by a Specified Column in PHP?
Sorting a Multidimensional Array by a Specified Column in PHP
To sort a multidimensional array in PHP by a specific column, use the built-in PHP functions usort or uasort. The key to sorting is to provide a custom comparison function that determines the order of the array elements.
Custom Comparison Function for Sorting
The custom comparison function takes two elements of the array as input and returns an integer:
Sorting by a Single Column
Let's say you have a multidimensional array called $data where each element represents a record with multiple columns. To sort the array by the 'name' column, use the following code:
usort($data, function($a, $b) { return strcmp($a['name'], $b['name']); });
This custom comparison function uses the strcmp function to compare the values of the 'name' column for each element. The sorted array will have the elements ordered alphabetically based on the 'name' column.
Sorting by Multiple Columns
To sort by multiple columns, pass additional parameters to the custom comparison function. For example, to sort by 'number' and then 'name':
usort($data, function($a, $b) { if ($a['number'] == $b['number']) { return strcmp($a['name'], $b['name']); } return $a['number'] - $b['number']; });
Advanced Features
You can also specify the following advanced features:
The above is the detailed content of How to Sort a Multidimensional Array by a Specified Column in PHP?. For more information, please follow other related articles on the PHP Chinese website!