How can the PHP code be optimized to achieve the desired result of grouping data by "timeline" and "ALL LOCATIONS"?

To optimize the PHP code to group data by "timeline" and "ALL LOCATIONS", we can modify the loop to check for the specific values and create separate arrays for each group. By using conditional statements within the loop, we can organize the data accordingly.

// Sample data array
$data = [
    ["timeline" => "2022-01-01", "location" => "Location A"],
    ["timeline" => "2022-01-01", "location" => "Location B"],
    ["timeline" => "2022-01-02", "location" => "Location A"],
    ["timeline" => "2022-01-02", "location" => "Location B"],
    ["timeline" => "2022-01-03", "location" => "Location A"],
    ["timeline" => "2022-01-03", "location" => "Location B"],
];

// Initialize arrays for grouping
$groupedData = [
    "timeline" => [],
    "ALL LOCATIONS" => []
];

// Group data by timeline and ALL LOCATIONS
foreach ($data as $item) {
    $groupedData["timeline"][$item["timeline"]][] = $item;
    $groupedData["ALL LOCATIONS"][] = $item;
}

// Output the grouped data
print_r($groupedData);