How can PHP be used to group identical data records together in a multidimensional array?

To group identical data records together in a multidimensional array in PHP, you can iterate through the data and use a key in the array to store the grouped records. By checking if a key already exists, you can append the data to the existing group or create a new group if the key is not found.

$data = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 1, 'name' => 'Doe']
];

$groupedData = [];

foreach ($data as $record) {
    $id = $record['id'];
    
    if (array_key_exists($id, $groupedData)) {
        $groupedData[$id][] = $record;
    } else {
        $groupedData[$id] = [$record];
    }
}

print_r($groupedData);