What is the alternative approach to grouping and displaying data in PHP when GROUP BY is not suitable?

When GROUP BY is not suitable for grouping and displaying data in PHP, an alternative approach is to use arrays to group the data. By iterating through the dataset and organizing the data into arrays based on a specific key, you can achieve the desired grouping effect. This allows for more flexibility and control over how the data is displayed.

// Sample data
$data = [
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Alice', 'age' => 28],
    ['name' => 'Bob', 'age' => 32],
];

// Group data by name
$groupedData = [];
foreach ($data as $row) {
    $name = $row['name'];
    if (!isset($groupedData[$name])) {
        $groupedData[$name] = [];
    }
    $groupedData[$name][] = $row;
}

// Display grouped data
foreach ($groupedData as $name => $group) {
    echo $name . ":\n";
    foreach ($group as $row) {
        echo " - " . $row['name'] . " (" . $row['age'] . ")\n";
    }
}