loilo / collection
Laravel 集合的扩展版本
1.0.0
2018-10-29 07:58 UTC
Requires
- php: ^7.1
- tightenco/collect: ^5.7
Requires (Dev)
- phpunit/phpunit: ^7.4
This package is auto-updated.
Last update: 2024-08-29 05:12:32 UTC
README
Laravel 集合的扩展版本
这是我非常个人化的 Laravel 的惊人 Collection 类的扩展(由 tightenco/collect 提取)。它添加了一些我经常需要的方法。
本项目的目标是向 Laravel 提供方法,通过在 laravel/ideas
提出建议来实现。
安装
composer require loilo/collection
方法
注意:以下所有代码示例中,
Collection
指的是Loilo\Collection\Collection
。
目录
insertBefore()
/insertAfter()
在参考项目之前/之后插入项目(修改集合)。
建议: #650(已拒绝)
详细信息: 规范
示例
在某个值之后插入项目列表
$c = Collection::make([ 10, 20, 30, 40 ]); $c->insertAfter(20, [ 24, 25, 26 ]); $c->all() === [ 10, 20, 24, 25, 26, 30, 40 ];
在某个键之后插入数据
$c = Collection::make([ 'name' => 'loilo/collection', 'version' => '1.0.0' ]); $c->insertAfter(function ($value, $key) { return $key === 'name'; }, [ 'description' => "An extended version of Laravel's collections" ]); $c->all() === [ 'name' => 'loilo/collection', 'description' => "An extended version of Laravel's collections", 'version' => '1.0.0' ];
mergeInBefore()
/mergeInAfter()
这些与 insertBefore()
/insertAfter()
相等,但不会修改集合。
extract()
从集合中提取结构,类似于高级 pluck()
。
详细信息: 规范
示例
从列表中取出某些项目
$c = Collection::make([ 1, 2, 3 ])->extract([ 0, 1 ]) $c->all() === [ 1, 2 ];
将集合转换为某种结构
$c = Collection::make([ 'a' => [ 'd' => 3, 'e' => 4 ], 'b' => [ 'd' => 5, 'e' => 6 ], 'c' => [ 'd' => 7, 'e' => 8 ] ]); $c->extract([ 'a' ])->all() === [ 'a' => [ 'd' => 3, 'e' => 4 ] ]; $c->extract([ '*' => [ 'd' ] ])->all() === [ 'a' => [ 'd' => 3 ], 'b' => [ 'd' => 5 ], 'c' => [ 'd' => 7 ] ];
rearrange()
此方法根据预定义的顺序重新排序集合。
Collection::make([ 'a', 'b', 'c' ]); ->rearrange([ 2, 0, 1 ]) ->all() === [ 'c', 'a', 'b' ];
无法重新排列的项目行为
当集合项目与新顺序不匹配时,它将被追加到排序项之后
Collection::make([ 'a', 'b', 'c' ]); ->rearrange([ 1 ]) ->all() === [ 'b', 'a', 'c' ];
此行为由 rearrange()
方法的第二个参数控制。默认行为 $c->rearrange([ ... ])
等同于 $c->rearrange([ ... ], Collection::UNARRANGEABLE_APPEND)
。
此参数的可能值
映射到重新排序的项目
默认情况下,传递给 rearrange()
的新顺序将映射到集合的键。但是,您可以将任何可调用对象作为方法的第三个参数传递,以自行映射顺序值
Collection::make([ 'a', 'b', 'c' ]); ->rearrange( [ 'b', 'a', 'c' ], Collection::UNARRANGEABLE_APPEND, function ($value, $key) { return $value; } ), ->all() === [ 'b', 'a', 'c' ];