Home >Backend Development >PHP Tutorial >How Can I Sort a Multi-Dimensional Array in PHP Using `usort()` and `uasort()`?
Many situations arise when the need to sort a multi-dimensional array is necessary. This can be achieved with the use of a user-defined comparison function within the usort() function.
Sorting by a Single Key Using usort()
To sort the given array by the value of the "order" key, we can define a sorting function as follows:
function sortByOrder($a, $b) { if ($a['order'] > $b['order']) { return 1; } elseif ($a['order'] < $b['order']) { return -1; } return 0; } usort($myArray, 'sortByOrder');
Alternatively, we can use an anonymous function:
usort($myArray, function($a, $b) { if ($a['order'] > $b['order']) { return 1; } elseif ($a['order'] < $b['order']) { return -1; } return 0; });
Multi-Dimensional Sorting
This approach can be extended to sort multi-dimensional arrays. For instance, to sort by "order" and then "suborder":
usort($myArray, function($a, $b) { $retval = $a['order'] <=> $b['order']; if ($retval == 0) { $retval = $a['suborder'] <=> $b['suborder']; } return $retval; });
Preserving Key Associations with uasort()
If you need to retain key associations, use uasort(). For comparison, refer to the manual's comparison of array sorting functions.
The above is the detailed content of How Can I Sort a Multi-Dimensional Array in PHP Using `usort()` and `uasort()`?. For more information, please follow other related articles on the PHP Chinese website!