Are there any best practices for grouping and displaying data in PHP arrays?

When grouping and displaying data in PHP arrays, it is best practice to use associative arrays where the keys represent the grouping criteria and the values are arrays of data that belong to that group. This makes it easier to organize and access the data based on specific criteria. Additionally, using functions like array_map or array_filter can help manipulate and filter the data before displaying it.

// Sample data
$data = [
    ['name' => 'John', 'age' => 25, 'country' => 'USA'],
    ['name' => 'Alice', 'age' => 30, 'country' => 'Canada'],
    ['name' => 'Bob', 'age' => 28, 'country' => 'USA'],
    ['name' => 'Eve', 'age' => 22, 'country' => 'Canada'],
];

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

// Display grouped data
foreach ($groupedData as $country => $users) {
    echo "Country: $country\n";
    foreach ($users as $user) {
        echo "Name: {$user['name']}, Age: {$user['age']}\n";
    }
    echo "\n";
}