How can user-defined functions and usort be utilized in PHP to achieve sorting based on multiple criteria?
To achieve sorting based on multiple criteria in PHP, you can use a user-defined function with `usort`. The user-defined function should compare the elements based on the desired criteria. Within the function, you can compare multiple criteria sequentially to achieve the desired sorting order.
// Sample array with multiple criteria for sorting
$data = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Alice', 'age' => 25],
];
// User-defined function to compare elements based on name and then age
function customSort($a, $b) {
if ($a['name'] == $b['name']) {
return $a['age'] - $b['age']; // Sort by age if names are equal
}
return strcmp($a['name'], $b['name']); // Sort by name
}
// Using usort with the customSort function
usort($data, 'customSort');
// Output the sorted array
print_r($data);