How can PHP be used to preprocess data before outputting it to ensure proper grouping and sorting?

When outputting data that needs to be properly grouped and sorted, PHP can be used to preprocess the data before displaying it. This can involve restructuring arrays, sorting elements, or applying any necessary transformations to ensure the desired output format. By manipulating the data in PHP before outputting it, you can control the grouping and sorting logic to meet your specific requirements.

// Sample data that needs to be grouped and sorted
$data = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 22],
    ['name' => 'Alice', 'age' => 28],
];

// Group data by name
$groupedData = [];
foreach ($data as $item) {
    $name = $item['name'];
    $groupedData[$name][] = $item;
}

// Sort grouped data by name
ksort($groupedData);

// Output the grouped and sorted data
foreach ($groupedData as $name => $items) {
    echo "Name: $name\n";
    foreach ($items as $item) {
        echo "Age: {$item['age']}\n";
    }
    echo "\n";
}