array_group_by
A PHP function to group an array by a key or set of keys shared between all array members.
Installation
To get the latest version of array_group_by
, simply require the project using Composer:
$ composer require jakezatecky/array_group_by
Need support for PHP 5.6? Then run the following:
$ composer require jakezatecky/array_group_by:^1.1.0
If you do not want to use Composer, you can just require
the src/array_group_by.php
file.
Usage
To use array_group_by
, simply pass an array with any number of keys to group by:
$records = [ [ 'state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus', ], [ 'state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole', ], [ 'state' => 'IN', 'city' => 'Plainfield', 'object' => 'Basketball', ], [ 'state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb', ], [ 'state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen', ], ]; $grouped = array_group_by($records, 'state', 'city');
Example output:
Array
(
[IN] => Array
(
[Indianapolis] => Array
(
[0] => Array
(
[state] => IN
[city] => Indianapolis
[object] => School bus
)
[1] => Array
(
[state] => IN
[city] => Indianapolis
[object] => Manhole
)
)
[Plainfield] => Array
(
[0] => Array
(
[state] => IN
[city] => Plainfield
[object] => Basketball
)
)
)
[CA] => Array
(
[San Diego] => Array
(
[0] => Array
(
[state] => CA
[city] => San Diego
[object] => Light bulb
)
)
[Mountain View] => Array
(
[0] => Array
(
[state] => CA
[city] => Mountain View
[object] => Space pen
)
)
)
)
Using a Callback
If more complex grouping behavior is desired, you can also pass in a callback function to determine the group key:
$grouped = array_group_by($records, function ($row) { return $row->city; });
版权声明:
1、该文章(资料)来源于互联网公开信息,我方只是对该内容做点评,所分享的下载地址为原作者公开地址。2、网站不提供资料下载,如需下载请到原作者页面进行下载。
3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考学习用!
4、如文档内容存在违规,或者侵犯商业秘密、侵犯著作权等,请点击“违规举报”。