Home > Article > Backend Development > Tips for multidimensional sorting of PHP arrays: from novice to proficient
Multidimensional array sorting skills: Single-dimensional sorting: use the sort() function Multi-dimensional sorting: use the callback function usort() Nested sorting: use multiple callback functions to sort different fields in a specified order Practical cases: by last name and date of birth Sorting Customer List
Array sorting is a basic yet powerful task in PHP. When it comes to multi-dimensional arrays, things get more complicated, but by using the right techniques, we can sort them easily and efficiently.
For single-dimensional sorting, we can use the sort()
function:
$array = ['a', 'c', 'b']; sort($array); print_r($array); // ['a', 'b', 'c']
Multidimensional sorting Need to use callback function:
$array = [ ['name' => 'Alice', 'age' => 30], ['name' => 'Bob', 'age' => 25], ['name' => 'Charlie', 'age' => 35], ]; usort($array, function ($a, $b) { return $a['age'] <=> $b['age']; }); print_r($array); // [ ['name' => 'Bob', 'age' => 25], ['name' => 'Alice', 'age' => 30], ['name' => 'Charlie', 'age' => 35] ]
Nested sorting Use multiple callback functions:
$array = [ ['name' => 'Alice', 'age' => 30], ['name' => 'Bob', 'age' => 25, 'city' => 'New York'], ['name' => 'Charlie', 'age' => 35, 'city' => 'London'], ]; usort($array, function ($a, $b) { if ($a['age'] == $b['age']) { return strcmp($a['city'], $b['city']); } return $a['age'] <=> $b['age']; }); print_r($array); // [ ['name' => 'Bob', 'age' => 25, 'city' => 'New York'], ['name' => 'Alice', 'age' => 30], ['name' => 'Charlie', 'age' => 35, 'city' => 'London'] ]
Customer list sorting: Sort the customer list based on the customer's last name and date of birth.
$customers = [ ['name' => 'John Doe', 'birthdate' => '1980-01-01'], ['name' => 'Jane Doe', 'birthdate' => '1985-03-08'], ['name' => 'Tom Smith', 'birthdate' => '1975-12-15'], ]; usort($customers, function ($a, $b) { if ($a['name'] == $b['name']) { return strtotime($a['birthdate']) <=> strtotime($b['birthdate']); } return strcmp($a['name'], $b['name']); });
With these tips, you can easily sort your project's PHP multidimensional arrays efficiently, regardless of their complexity.
The above is the detailed content of Tips for multidimensional sorting of PHP arrays: from novice to proficient. For more information, please follow other related articles on the PHP Chinese website!