多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 将一个集合拆分2个集合 在 Laravel v5.3.27 之后,collection 新增了一个 partition 方法,该方法可以根据传入的条件 将原来的 collection 分成两个 collection,比如: ~~~ $collection = collect([1, 2, 3, 4, 5, 6, 7]); $items = $collection->partition(function ($item) { return $item < 4; }); ~~~ 这样会得到下面的结果: ~~~ Collection {#190 ▼ #items: array:2 [▼ 0 => Collection {#183 ▼ #items: array:3 [▼ 0 => 1 1 => 2 2 => 3 ] } 1 => Collection {#189 ▼ #items: array:4 [▼ 3 => 4 4 => 5 5 => 6 6 => 7 ] } ] } ~~~ 结果返回的两个都是 collection 对象。 # where方法 Laravel 5.3 开始,在 collection 层面也开始支持使用 where 方法,对于一些应用场景非常的适用: 比如在没有 where 方法的使用,我们可能会使用 filter 方法来达到一定的目的: ~~~ $vips = $users->filter(function ($user) { return $user->role === 'vip'; }); ~~~ 但是在 5.3 中,你可以直接这样使用: ~~~ $vips = $users->where('role', 'vip'); ~~~ Nice and clean ! 更甚至的是,你还可以传入比较符号,如 >, < 等: ~~~ $members = $users->where('role', '!==', 'vip'); $expert = $users->where('experience', '>', 500); ~~~ where 方法无疑是为 collection 添加了更方便的过滤和查找方法,希望大家在这样的场景之下可以用起来。