What are some best practices for grouping data in PHP arrays?

When grouping data in PHP arrays, it is best to use associative arrays where the keys represent the group names and the values are arrays containing the grouped data. This allows for easy access and manipulation of the grouped data. Additionally, using functions like array_push() or array_merge() can help in adding elements to the grouped arrays.

$data = [
    ['group' => 'A', 'value' => 1],
    ['group' => 'B', 'value' => 2],
    ['group' => 'A', 'value' => 3],
    ['group' => 'B', 'value' => 4]
];

$groupedData = [];

foreach ($data as $item) {
    $group = $item['group'];
    
    if (!isset($groupedData[$group])) {
        $groupedData[$group] = [];
    }
    
    $groupedData[$group][] = $item['value'];
}

print_r($groupedData);