How can you efficiently group data in multidimensional arrays based on a specific key in PHP?

When working with multidimensional arrays in PHP, you may need to efficiently group data based on a specific key. One way to achieve this is by using the array_reduce() function along with a custom callback function. This allows you to iterate over the array and group the data based on the specified key.

$data = [
    ['id' => 1, 'name' => 'John', 'group' => 'A'],
    ['id' => 2, 'name' => 'Jane', 'group' => 'B'],
    ['id' => 3, 'name' => 'Alice', 'group' => 'A'],
    ['id' => 4, 'name' => 'Bob', 'group' => 'B']
];

$groupedData = array_reduce($data, function($result, $item) {
    $result[$item['group']][] = $item;
    return $result;
}, []);

print_r($groupedData);