Sorting multidimensional arrays is a common task in PHP development. Mastering proper sorting methods can significantly improve data handling efficiency and code readability.
Assume we have an array containing student names and their scores. We want to sort it primarily by name in ascending order and then by score in descending order.
$students = [
['name' => 'Alice', 'score' => 90],
['name' => 'Bob', 'score' => 85],
['name' => 'Charlie', 'score' => 95],
['name' => 'Dave', 'score' => 80],
];
By defining a comparison function, you can precisely control the sorting rules. The following function first compares names, and if the names are the same, it compares scores:
function compare_students($a, $b) {
if ($a['name'] == $b['name']) {
return $b['score'] <=> $a['score']; // Score descending
}
return strcmp($a['name'], $b['name']); // Name ascending
}
Use the usort() function to perform the sorting:
usort($students, 'compare_students');
PHP 7.4 introduced simplified anonymous functions, making the code more concise:
uasort($students, function($a, $b) {
if ($a['name'] == $b['name']) {
return $b['score'] <=> $a['score'];
}
return strcmp($a['name'], $b['name']);
});
The comparison function accepts two array elements as parameters and returns an integer indicating their order relationship. Here, strcmp() sorts names in ascending order, and if the names are identical, the spaceship operator <=> sorts scores in descending order.
After sorting, the output looks like this:
print_r($students);
The array is sorted alphabetically by name, and if names are the same, scores are sorted from highest to lowest.
Understanding the core concepts and methods for sorting multidimensional arrays in PHP helps developers handle complex sorting tasks with flexibility. Using custom comparison functions alongside PHP’s built-in sorting functions leads to clean and efficient code.