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.
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:
Example of grouping an array of arrays (subarrays) by the value of a specific key in each subarray in PHP
php— editable, runs on the server
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
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.