How can the array_sort_by_subarray_item() function be used effectively in PHP for sorting arrays?

To use the array_sort_by_subarray_item() function effectively in PHP for sorting arrays, you can pass the array to be sorted as the first parameter and the key of the subarray item you want to sort by as the second parameter. This function will sort the main array based on the values of the specified subarray item.

function array_sort_by_subarray_item($array, $key) {
    usort($array, function($a, $b) use ($key) {
        return $a[$key] <=> $b[$key];
    });
    return $array;
}

// Example usage
$students = [
    ['name' => 'Alice', 'age' => 20],
    ['name' => 'Bob', 'age' => 25],
    ['name' => 'Charlie', 'age' => 22]
];

$sorted_students = array_sort_by_subarray_item($students, 'age');

print_r($sorted_students);