jakezatecky / array_group_by
一个根据给定键或键的值对数组进行分组/分割的函数。
v2.0.0
2017-10-07 18:50 UTC
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: ^6.0.6
README
一个PHP函数,可以根据所有数组成员之间共享的键或键集对数组进行分组。
安装
要获取最新版本的 array_group_by
,只需使用Composer引用项目即可
$ composer require jakezatecky/array_group_by
需要支持PHP 5.6吗?那么运行以下命令
$ composer require jakezatecky/array_group_by:^1.1.0
如果您不想使用Composer,只需直接 require
src/array_group_by.php
文件。
用法
要使用 array_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');
示例输出
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
)
)
)
)
使用回调函数
如果您希望有更复杂的分组行为,也可以传递一个回调函数来确定分组键
$grouped = array_group_by($records, function ($row) { return $row->city; });