PHP
Group an Array of Associative Arrays by a Key
Organize and group elements within a PHP array of associative arrays by a common key, similar to a 'GROUP BY' SQL clause, for structured data output or processing.
$students = [
['name' => 'Alice', 'grade' => 'A', 'major' => 'CS'],
['name' => 'Bob', 'grade' => 'B', 'major' => 'Math'],
['name' => 'Charlie', 'grade' => 'A', 'major' => 'CS'],
['name' => 'David', 'grade' => 'C', 'major' => 'Math'],
['name' => 'Eve', 'grade' => 'A', 'major' => 'Physics'],
];
$groupedByMajor = [];
foreach ($students as $student) {
$major = $student['major'];
if (!isset($groupedByMajor[$major])) {
$groupedByMajor[$major] = [];
}
$groupedByMajor[$major][] = $student;
}
/* $groupedByMajor will be:
[
'CS' => [
['name' => 'Alice', 'grade' => 'A', 'major' => 'CS'],
['name' => 'Charlie', 'grade' => 'A', 'major' => 'CS']
],
'Math' => [
['name' => 'Bob', 'grade' => 'B', 'major' => 'Math'],
['name' => 'David', 'grade' => 'C', 'major' => 'Math']
],
'Physics' => [
['name' => 'Eve', 'grade' => 'A', 'major' => 'Physics']
]
]
*/
How it works: This snippet demonstrates how to group an array of associative arrays based on a specific key (e.g., 'major'). It iterates through the original array, using the value of the chosen key as the new key for the grouped array. If the group key doesn't exist, it's initialized as an empty array before appending the current element. This creates a new array where elements are organized into sub-arrays by their common 'major'.