How can closures be utilized in PHP to sort multi-dimensional arrays efficiently?
To efficiently sort multi-dimensional arrays in PHP using closures, we can use the `usort()` function along with a closure that defines the custom sorting logic. The closure can access the values of the sub-arrays for comparison during the sorting process.
// Sample multi-dimensional array
$multiDimArray = [
['name' => 'John', 'age' => 30],
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 35]
];
// Sort the multi-dimensional array by 'age' in ascending order
usort($multiDimArray, function($a, $b) {
return $a['age'] - $b['age'];
});
// Output the sorted array
print_r($multiDimArray);