Group array by subarray values
In PHP, you can group an array of arrays (subarrays) by the value of a specific key in each subarray using the array_reduce()
function. Here is an example:
<?php
$data = [['id' => 1, 'name' => 'Alice', 'group' => 'A'], ['id' => 2, 'name' => 'Bob', 'group' => 'B'], ['id' => 3, 'name' => 'Charlie', 'group' => 'A'], ['id' => 4, 'name' => 'Dave', 'group' => 'B']];
$grouped = array_reduce(
$data,
function ($carry, $item) {
$carry[$item['group']][] = $item;
return $carry;
},
[]
);
print_r($grouped);
Watch a video course
Learn object oriented PHP
This will group the subarrays by the value of the 'group' key, resulting in the following output:
Array ( [A] => Array ( [0] => Array ( [id] => 1 [name] => Alice [group] => A ) [1] => Array ( [id] => 3 [name] => Charlie [group] => A ) ) [B] => Array ( [0] => Array ( [id] => 2 [name] => Bob [group] => B ) [1] => Array ( [id] => 4 [name] => Dave [group] => B ) ) )
You can group by any key which exist in subarray as per requirement.