How can PHP arrays be grouped by location for better organization and display?

To group PHP arrays by location for better organization and display, you can use a multidimensional array where the key represents the location. Each location key can then contain an array of data related to that location. This way, you can easily organize and access data based on location.

// Sample data with locations
$data = array(
    array('name' => 'John', 'location' => 'New York'),
    array('name' => 'Jane', 'location' => 'Los Angeles'),
    array('name' => 'Alice', 'location' => 'New York'),
);

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

// Display grouped data
foreach ($groupedData as $location => $items) {
    echo "Location: $location\n";
    foreach ($items as $item) {
        echo "Name: " . $item['name'] . "\n";
    }
    echo "\n";
}