What are some best practices for sorting arrays with multiple attributes in PHP?
When sorting arrays with multiple attributes in PHP, one common approach is to use the `usort()` function along with a custom comparison function. This function should compare the desired attributes of each element in the array to determine the sorting order. By customizing the comparison logic, you can sort the array based on multiple attributes in a flexible and efficient manner.
// Sample array with multiple attributes
$users = [
['name' => 'John', 'age' => 30],
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 35],
];
// Custom comparison function to sort by name and then age
usort($users, function($a, $b) {
if ($a['name'] == $b['name']) {
return $a['age'] - $b['age'];
}
return strcmp($a['name'], $b['name']);
});
// Output sorted array
print_r($users);