集合

    类提供了一个更具可读性和更便于处理数组数据的封装。具体例子请查看下面代码。我们使用 collect 辅助函数从数组中创建一个新的集合实例,对其中每一个元素执行 strtoupper 函数之后再删除所有的空元素:

    正如你所见, Collection 类允许你链式调用其它方法,以达到在底层数组上流畅的执行 map 和 reduce 操作,通常,集合是不可变的,这意味着每一个 Collection 方法都会返回一个新的 Collection 实例。

    如上所述, collect 辅助函数会为指定的数组返回一个新的 Illuminate\Support\Collection 实例。因此,我们可以这样轻松的创建一个集合:

    1. $collection = collect([1, 2, 3]);

    扩展集合

    集合都是「可宏扩展」(macroable)的,它允许你在执行时将其它方法添加到 Collection 类。例如,通过下面的代码在 Collection 类中添加一个 toUpper 方法:

    1. use Illuminate\Support\Str;
    2. Collection::macro('toUpper', function () {
    3. return $this->map(function ($value) {
    4. return Str::upper($value);
    5. });
    6. });
    7. $collection = collect(['first', 'second']);
    8. $upper = $collection->toUpper();
    9. // ['FIRST', 'SECOND']

    通常,你应该在 内声明集合宏。

    接下来的文档内容,我们会探讨 Collection 类的每个方法。请牢记,所有方法都可以通过链式访问的形式优雅的操作数组。而且,几乎所有的方法都会返回一个新的 Collection 实例,允许你在必要时保存集合的原始副本:

    averagechunkcombinecontainscountdddiffAssocdumpeachSpreadexceptfirstflatMapflipforPagegroupByimplodeintersectByKeysisNotEmptykeysmacromapmapSpreadmapWithKeysmedianminnthpadpipepoppullputreducereverseshiftslicesortsortByDescsortKeysDescsplittaketimestoJsonunionuniqueStrictunlessEmptyunwrapwhenwhenNotEmptywhereStrictwhereInwhereInstanceOfwhereNotInwrap

    all()

    all 方法返回该集合表示的底层数组:

    1. collect([1, 2, 3])->all();
    2. // [1, 2, 3]

    average()

    方法的别名。

    avg()

    avg 方法返回给定键的 平均值

    1. $average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
    2. // 20
    3. $average = collect([1, 1, 2, 4])->avg();
    4. // 2

    chunk()

    chunk 方法将集合拆成多个给定大小的小集合:

    1. $collection = collect([1, 2, 3, 4, 5, 6, 7]);
    2. $chunks = $collection->chunk(4);
    3. $chunks->toArray();
    4. // [[1, 2, 3, 4], [5, 6, 7]]

    这个方法在使用网格系统的 中特别适用,例如 Bootstrap。 想象你有一个 模型的集合要在网格中显示:

    1. @foreach ($products->chunk(3) as $chunk)
    2. <div class="row">
    3. @foreach ($chunk as $product)
    4. <div class="col-xs-4">{{ $product->name }}</div>
    5. @endforeach
    6. </div>
    7. @endforeach

    collapse()

    collapse 方法将多个数组的集合合并成一个数组的集合:

    1. $collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
    2. $collapsed = $collection->collapse();
    3. $collapsed->all();
    4. // [1, 2, 3, 4, 5, 6, 7, 8, 9]

    combine()

    combine 方法可以将一个集合的值作为键,再将另一个数组或集合的值作为值合并成一个集合:

    1. $collection = collect(['name', 'age']);
    2. $combined = $collection->combine(['George', 29]);
    3. $combined->all();
    4. // ['name' => 'George', 'age' => 29]

    concat()

    concat 方法将给定的 数组 或集合值追加到集合的末尾:

    1. $collection = collect(['John Doe']);
    2. $concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
    3. $concatenated->all();
    4. // ['John Doe', 'Jane Doe', 'Johnny Doe']

    contains()

    contains 方法判断集合是否包含指定的集合项:

    1. $collection = collect(['name' => 'Desk', 'price' => 100]);
    2. $collection->contains('Desk');
    3. // true
    4. $collection->contains('New York');
    5. // false

    你也可以使用 contains 方法传递一组键 / 值对,可以判断该键 / 值对是否存在于集合中:

    1. $collection = collect([
    2. ['product' => 'Desk', 'price' => 200],
    3. ['product' => 'Chair', 'price' => 100],
    4. ]);
    5. $collection->contains('product', 'Bookcase');
    6. // false

    最后,你也可以用 contains 方法传递一个回调函数来执行自己的真实测试:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $collection->contains(function ($value, $key) {
    3. return $value > 5;
    4. });
    5. // false

    contains 方法在检查集合项的值时使用「宽松」比较,这意味着具有整数值的字符串将被视为等于相同值的整数。相反 containsStrict 方法则是使用「严格」比较进行过滤。

    containsStrict()

    这个方法和 方法类似,但是它却是使用了「严格」比较来比较所有的值。

    count()

    count 方法返回这个集合内集合项的总数量:

    1. $collection = collect([1, 2, 3, 4]);
    2. $collection->count();
    3. // 4

    crossJoin()

    crossJoin 方法交叉连接指定数组或集合的值,返回所有可能排列的笛卡尔积:

    1. $collection = collect([1, 2]);
    2. $matrix = $collection->crossJoin(['a', 'b']);
    3. $matrix->all();
    4. /*
    5. [
    6. [1, 'a'],
    7. [1, 'b'],
    8. [2, 'a'],
    9. [2, 'b'],
    10. ]
    11. */
    12. $collection = collect([1, 2]);
    13. $matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
    14. $matrix->all();
    15. /*
    16. [
    17. [1, 'a', 'I'],
    18. [1, 'a', 'II'],
    19. [1, 'b', 'I'],
    20. [1, 'b', 'II'],
    21. [2, 'a', 'I'],
    22. [2, 'a', 'II'],
    23. [2, 'b', 'I'],
    24. [2, 'b', 'II'],
    25. ]
    26. */

    dd()

    dd 方法用于打印集合项并中断脚本执行:

    1. $collection = collect(['John Doe', 'Jane Doe']);
    2. $collection->dd();
    3. /*
    4. Collection {
    5. #items: array:2 [
    6. 0 => "John Doe"
    7. 1 => "Jane Doe"
    8. ]
    9. }
    10. */

    如果你不想中断执行脚本,请使用 dump 方法代替。

    diff()

    diff 方法将集合与其它集合或纯 PHP 数组 进行值的比较。然后返回原集合中存在而指定集合中不存在的值:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $diff = $collection->diff([2, 4, 6, 8]);
    3. $diff->all();
    4. // [1, 3, 5]

    diffAssoc()

    diffAssoc 方法与另外一个集合或基于它的键和值的 PHP 数组 进行比较。这个方法将会返回原集合不存在于指定集合的键 / 值对:

    1. $collection = collect([
    2. 'color' => 'orange',
    3. 'type' => 'fruit',
    4. 'remain' => 6
    5. ]);
    6. $diff = $collection->diffAssoc([
    7. 'color' => 'yellow',
    8. 'type' => 'fruit',
    9. 'remain' => 3,
    10. 'used' => 6
    11. ]);
    12. $diff->all();
    13. // ['color' => 'orange', 'remain' => 6]

    diffKeys()

    diffKeys 方法和另外一个集合或 PHP 数组 的键进行比较,然后返回原集合中存在而指定集合中不存在键所对应的键 / 值对:

    1. $collection = collect([
    2. 'one' => 10,
    3. 'two' => 20,
    4. 'three' => 30,
    5. 'four' => 40,
    6. 'five' => 50,
    7. ]);
    8. $diff = $collection->diffKeys([
    9. 'two' => 2,
    10. 'four' => 4,
    11. 'six' => 6,
    12. 'eight' => 8,
    13. ]);
    14. $diff->all();
    15. // ['one' => 10, 'three' => 30, 'five' => 50]

    dump()

    dump 方法用于打印集合项:

    1. $collection = collect(['John Doe', 'Jane Doe']);
    2. $collection->dump();
    3. /*
    4. Collection {
    5. #items: array:2 [
    6. 0 => "John Doe"
    7. 1 => "Jane Doe"
    8. ]
    9. }
    10. */

    如果要在打印集合后终止执行脚本,请使用 方法代替。

    each()

    each 方法用于循环集合项并将其传递到回调函数中:

    1. $collection->each(function ($item, $key) {
    2. //
    3. });

    如果你想中断对集合项的循环,那么就在你的回调函数中返回 false

    1. $collection->each(function ($item, $key) {
    2. if (/* 某些条件 */) {
    3. return false;
    4. }
    5. });

    eachSpread()

    eachSpread 方法用于循环集合项,将每个嵌套集合项的值传递给回调函数:

    1. $collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
    2. $collection->eachSpread(function ($name, $age) {
    3. //
    4. });

    你可以通过在回调函数里返回 false 来中断循环:

    1. $collection->eachSpread(function ($name, $age) {
    2. return false;
    3. });

    every()

    every 方法可用于验证集合中的每一个元素是否通过指定的条件测试:

    1. collect([1, 2, 3, 4])->every(function ($value, $key) {
    2. return $value > 2;
    3. });
    4. // false

    如果集合为空, every 将返回 true:

    1. $collection = collect([]);
    2. $collection->every(function($value, $key) {
    3. return $value > 2;
    4. });
    5. // true

    except()

    except 方法返回集合中除了指定键之外的所有集合项:

    1. $collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
    2. $filtered = $collection->except(['price', 'discount']);
    3. $filtered->all();
    4. // ['product_id' => 1]

    except 对应的是 only 方法。

    filter()

    filter 方法使用给定的回调函数过滤集合,只保留那些通过指定条件测试的集合项:

    1. $collection = collect([1, 2, 3, 4]);
    2. $filtered = $collection->filter(function ($value, $key) {
    3. return $value > 2;
    4. });
    5. $filtered->all();
    6. // [3, 4]

    如果没有提供回调函数,集合中所有返回 false 的元素都会被移除:

    1. $collection = collect([1, 2, 3, null, false, '', 0, []]);
    2. $collection->filter()->all();
    3. // [1, 2, 3]

    filter 对应的是 方法。

    first()

    first 方法返回集合中通过指定条件测试的第一个元素:

    1. collect([1, 2, 3, 4])->first(function ($value, $key) {
    2. return $value > 2;
    3. });
    4. // 3

    你也可以不传入参数调用 first 方法来获取集合中的第一个元素。如果集合为空,则会返回 null

    1. collect([1, 2, 3, 4])->first();
    2. // 1

    firstWhere()

    firstWhere 方法返回集合中含有指定键 / 值对的第一个元素:

    1. $collection = collect([
    2. ['name' => 'Regena', 'age' => null],
    3. ['name' => 'Linda', 'age' => 14],
    4. ['name' => 'Diego', 'age' => 23],
    5. ['name' => 'Linda', 'age' => 84],
    6. ]);
    7. $collection->firstWhere('name', 'Linda');
    8. // ['name' => 'Linda', 'age' => 14]

    你也可以使用运算符来调用 firstWhere 方法:

    1. $collection->firstWhere('age', '>=', 18);
    2. // ['name' => 'Diego', 'age' => 23]

    where 方法一样,你可以将一个参数传递给 firstWhere 方法。在这种情况下, firstWhere 方法将返回指定键的值为「真」的第一个集合项:

    1. $collection->firstWhere('age');
    2. // ['name' => 'Linda', 'age' => 14]

    flatMap()

    flatMap 方法遍历集合并将其中的每个值传递到给定的回调函数。可以通过回调函数修改集合项并返回它们,从而形成一个被修改过的新集合。然后,集合转化的数组是同级的:

    1. $collection = collect([
    2. ['name' => 'Sally'],
    3. ['school' => 'Arkansas'],
    4. ['age' => 28]
    5. ]);
    6. $flattened = $collection->flatMap(function ($values) {
    7. return array_map('strtoupper', $values);
    8. });
    9. $flattened->all();
    10. // ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

    flatten()

    flatten 方法将多维集合转为一维集合:

    1. $collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
    2. $flattened = $collection->flatten();
    3. $flattened->all();
    4. // ['taylor', 'php', 'javascript'];

    你可以选择性地传入「深度」参数:

    1. $collection = collect([
    2. 'Apple' => [
    3. ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    4. ],
    5. 'Samsung' => [
    6. ['name' => 'Galaxy S7', 'brand' => 'Samsung']
    7. ],
    8. ]);
    9. $products = $collection->flatten(1);
    10. $products->values()->all();
    11. /*
    12. [
    13. ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    14. ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
    15. ]
    16. */

    在这个例子里,调用 flatten 时不传入深度参数的话也会将嵌套数组转成一维的,然后返回 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']。传入深度参数能让你限制设置返回数组的层数。

    flip()

    flip 方法将集合的键和对应的值进行互换:

    1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
    2. $flipped = $collection->flip();
    3. $flipped->all();
    4. // ['taylor' => 'name', 'laravel' => 'framework']

    forget()

    forget 方法将通过指定的键来移除集合中对应的内容:

    1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
    2. $collection->forget('name');
    3. $collection->all();
    4. // ['framework' => 'laravel']

    注意:与大多数集合的方法不同的是, forget 不会返回修改后的新集合;它会直接修改原集合。

    forPage()

    forPage 方法返回一个含有指定页码数集合项的新集合。这个方法接受页码数作为其第一个参数,每页显示的项数作为其第二个参数:

    1. $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
    2. $chunk = $collection->forPage(2, 3);
    3. $chunk->all();
    4. // [4, 5, 6]

    get()

    get 方法返回指定键的集合项,如果该键在集合中不存在,则返回 null

    1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
    2. $value = $collection->get('name');
    3. // taylor

    你可以任选一个默认值作为第二个参数传递:

    1. $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
    2. $value = $collection->get('foo', 'default-value');
    3. // default-value

    你甚至可以将一个回调函数作为默认值传递。如果指定的键不存在,就会返回回调函数的结果:

    1. $collection->get('email', function () {
    2. return 'default-value';
    3. });
    4. // default-value

    groupBy()

    groupBy 方法根据指定键对集合项进行分组:

    1. $collection = collect([
    2. ['account_id' => 'account-x10', 'product' => 'Chair'],
    3. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    4. ['account_id' => 'account-x11', 'product' => 'Desk'],
    5. ]);
    6. $grouped = $collection->groupBy('account_id');
    7. $grouped->toArray();
    8. /*
    9. [
    10. ['account_id' => 'account-x10', 'product' => 'Chair'],
    11. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    12. ],
    13. 'account-x11' => [
    14. ['account_id' => 'account-x11', 'product' => 'Desk'],
    15. ],
    16. ]
    17. */

    你可以传递一个回调函数用来代替一个字符串的 。这个回调函数应该返回你希望用来分组的键的值:

    1. $grouped = $collection->groupBy(function ($item, $key) {
    2. return substr($item['account_id'], -3);
    3. });
    4. $grouped->toArray();
    5. /*
    6. [
    7. 'x10' => [
    8. ['account_id' => 'account-x10', 'product' => 'Chair'],
    9. ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    10. ],
    11. 'x11' => [
    12. ['account_id' => 'account-x11', 'product' => 'Desk'],
    13. ],
    14. ]
    15. */

    可以传递一个数组用于多重分组标准。每一个数组元素将对应多维数组内的相应级别:

    has()

    has 方法判断集合中是否存在指定键:

    1. $collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
    2. $collection->has('product');
    3. // true
    4. $collection->has(['product', 'amount']);
    5. // true
    6. $collection->has(['amount', 'price']);
    7. // false

    implode()

    1. $collection = collect([
    2. ['account_id' => 1, 'product' => 'Desk'],
    3. ['account_id' => 2, 'product' => 'Chair'],
    4. ]);
    5. $collection->implode('product', ', ');
    6. // Desk, Chair

    如果集合中包含简单的字符串或数值,只需要传入「拼接」用的字符串作为该方法的唯一参数即可:

    1. collect([1, 2, 3, 4, 5])->implode('-');
    2. // '1-2-3-4-5'

    intersect()

    intersect 方法从原集合中移除在指定 数组 或集合中不存在的任何值。生成的集合将会保留原集合的键:

    1. $collection = collect(['Desk', 'Sofa', 'Chair']);
    2. $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
    3. $intersect->all();
    4. // [0 => 'Desk', 2 => 'Chair']

    intersectByKeys()

    intersectByKeys 方法从原集合中移除在指定 数组 或集合中不存在的任何键:

    1. $collection = collect([
    2. 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
    3. ]);
    4. $intersect = $collection->intersectByKeys([
    5. 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
    6. ]);
    7. $intersect->all();
    8. // ['type' => 'screen', 'year' => 2009]

    isEmpty()

    如果集合为空,isEmpty 方法返回 true,否则,返回 false

    1. collect([])->isEmpty();
    2. // true

    isNotEmpty()

    如果集合不为空,isNotEmpty 方法返回 true,否则,返回 false

    1. collect([])->isNotEmpty();
    2. // false

    keyBy()

    keyBy 方法以指定的键作为集合的键。如果多个集合项具有相同的键,则只有最后一个集合项会显示在新集合中:

    1. $collection = collect([
    2. ['product_id' => 'prod-100', 'name' => 'Desk'],
    3. ['product_id' => 'prod-200', 'name' => 'Chair'],
    4. ]);
    5. $keyed = $collection->keyBy('product_id');
    6. $keyed->all();
    7. /*
    8. [
    9. 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    10. 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    11. ]
    12. */

    你还可以在这个方法传递一个回调函数。该回调函数返回的值会作为该集合的键:

    1. $keyed = $collection->keyBy(function ($item) {
    2. return strtoupper($item['product_id']);
    3. });
    4. $keyed->all();
    5. /*
    6. [
    7. 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    8. 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    9. ]
    10. */

    keys()

    keys 方法返回集合中所有的键:

    1. $collection = collect([
    2. 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    3. 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    4. ]);
    5. $keys = $collection->keys();
    6. $keys->all();
    7. // ['prod-100', 'prod-200']

    last()

    last 方法返回集合中通过指定条件测试的最后一个元素:

    1. collect([1, 2, 3, 4])->last(function ($value, $key) {
    2. return $value < 3;
    3. });
    4. // 2

    你也可以不传入参数调用 last 方法来获取集合中的最后一个元素。如果集合为空,则返回 null

    1. collect([1, 2, 3, 4])->last();
    2. // 4

    macro()

    静态 macro 方法允许你在运行时将方法添加至 Collection 类。关于更多信息,请参阅 的文档。

    make()

    静态 make 方法可以创建一个新的集合实例。请参阅 创建集合 部分。

    map()

    map 方法遍历集合并将每一个值传入给定的回调函数。该回调函数可以任意修改集合项并返回,从而生成被修改过集合项的新集合:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $multiplied = $collection->map(function ($item, $key) {
    3. return $item * 2;
    4. });
    5. $multiplied->all();
    6. // [2, 4, 6, 8, 10]

    mapInto()

    mapInto() 方法可以迭代集合,通过将值传递给构造函数来创建给定类的新实例:

    1. class Currency
    2. {
    3. /**
    4. * Create a new currency instance.
    5. *
    6. * @param string $code
    7. * @return void
    8. */
    9. function __construct(string $code)
    10. {
    11. $this->code = $code;
    12. }
    13. }
    14. $collection = collect(['USD', 'EUR', 'GBP']);
    15. $currencies = $collection->mapInto(Currency::class);
    16. $currencies->all();
    17. // [Currency('USD'), Currency('EUR'), Currency('GBP')]

    mapSpread()

    mapSpread 方法可以遍历集合项,将每个嵌套项值给指定的回调函数。该回调函数可以自由修改该集合项并返回,从而生成被修改过集合项的新集合:

    1. $collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
    2. $chunks = $collection->chunk(2);
    3. $sequence = $chunks->mapSpread(function ($even, $odd) {
    4. return $even + $odd;
    5. });
    6. $sequence->all();
    7. // [1, 5, 9, 13, 17]

    mapToGroups()

    mapToGroups 方法通过给定的回调函数对集合项进行分组。该回调函数应该返回一个包含单个键 / 值对的关联数组,从而生成一个分组值的新集合:

    1. $collection = collect([
    2. [
    3. 'name' => 'John Doe',
    4. 'department' => 'Sales',
    5. ],
    6. [
    7. 'name' => 'Jane Doe',
    8. 'department' => 'Sales',
    9. ],
    10. [
    11. 'name' => 'Johnny Doe',
    12. 'department' => 'Marketing',
    13. ]
    14. ]);
    15. $grouped = $collection->mapToGroups(function ($item, $key) {
    16. return [$item['department'] => $item['name']];
    17. });
    18. $grouped->toArray();
    19. /*
    20. [
    21. 'Sales' => ['John Doe', 'Jane Doe'],
    22. 'Marketing' => ['Johnny Doe'],
    23. ]
    24. */
    25. $grouped->get('Sales')->all();
    26. // ['John Doe', 'Jane Doe']

    mapWithKeys()

    mapWithKeys 方法遍历集合并将每个值传入给定的回调函数。该回调函数将返回一个包含单个键 / 值对的关联数组:

    1. $collection = collect([
    2. [
    3. 'name' => 'John',
    4. 'department' => 'Sales',
    5. 'email' => 'john@example.com'
    6. ],
    7. [
    8. 'name' => 'Jane',
    9. 'department' => 'Marketing',
    10. 'email' => 'jane@example.com'
    11. ]
    12. ]);
    13. $keyed = $collection->mapWithKeys(function ($item) {
    14. return [$item['email'] => $item['name']];
    15. });
    16. $keyed->all();
    17. /*
    18. [
    19. 'john@example.com' => 'John',
    20. 'jane@example.com' => 'Jane',
    21. ]
    22. */

    max()

    max 方法返回指定键的最大值:

    1. $max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
    2. // 20
    3. $max = collect([1, 2, 3, 4, 5])->max();
    4. // 5

    median()

    median 方法返回指定键的 :

    1. $median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
    2. // 15
    3. $median = collect([1, 1, 2, 4])->median();
    4. // 1.5

    merge()

    merge 方法将合并指定的数组或集合到原集合。如果给定的集合项的字符串键与原集合中的字符串键相匹配,则指定集合项的值将覆盖原集合的值:

    1. $collection = collect(['product_id' => 1, 'price' => 100]);
    2. $merged = $collection->merge(['price' => 200, 'discount' => false]);
    3. $merged->all();
    4. // ['product_id' => 1, 'price' => 200, 'discount' => false]

    如果指定的集合项的键是数字,这些值将会追加到集合的末尾:

    1. $collection = collect(['Desk', 'Chair']);
    2. $merged = $collection->merge(['Bookcase', 'Door']);
    3. $merged->all();
    4. // ['Desk', 'Chair', 'Bookcase', 'Door']

    min()

    min 方法返回指定键的最小值:

    1. $min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
    2. // 10
    3. $min = collect([1, 2, 3, 4, 5])->min();
    4. // 1

    mode()

    mode 方法返回指定键的 众数) :

    1. $mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
    2. // [10]
    3. $mode = collect([1, 1, 2, 4])->mode();
    4. // [1]

    nth()

    nth 方法创建由每隔 n 个元素组成的一个新集合:

    1. $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
    2. $collection->nth(4);
    3. // ['a', 'e']

    你可以选择传入一个偏移位置作为第二个参数:

    1. $collection->nth(4, 1);
    2. // ['b', 'f']

    only()

    only 方法返回集合中所有指定键的集合项:

    1. $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
    2. $filtered = $collection->only(['product_id', 'name']);
    3. $filtered->all();
    4. // ['product_id' => 1, 'name' => 'Desk']

    only 对应的是 方法。

    pad()

    pad 方法将使用给定的值填充数组,直到数组达到指定的大小。该方法的行为与 array_pad PHP 函数功能类似。

    要填充到左侧,你应该使用负值。如果给定大小的绝对值小于或等于数组的长度,则不会发生填充:

    1. $collection = collect(['A', 'B', 'C']);
    2. $filtered = $collection->pad(5, 0);
    3. $filtered->all();
    4. // ['A', 'B', 'C', 0, 0]
    5. $filtered = $collection->pad(-5, 0);
    6. $filtered->all();
    7. // [0, 0, 'A', 'B', 'C']

    partition()

    partition 方法可以和 PHP 函数中的 list 结合使用,用来分开通过指定条件的元素以及那些不通过指定条件的元素:

    1. $collection = collect([1, 2, 3, 4, 5, 6]);
    2. list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) {
    3. return $i < 3;
    4. });
    5. $underThree->all();
    6. // [1, 2]
    7. $equalOrAboveThree->all();
    8. // [3, 4, 5, 6]

    pipe()

    pipe 方法将集合传给指定的回调函数并返回结果:

    1. $collection = collect([1, 2, 3]);
    2. $piped = $collection->pipe(function ($collection) {
    3. return $collection->sum();
    4. });
    5. // 6

    pluck()

    pluck 方法可以获取集合中指定键对应的所有值:

    1. $collection = collect([
    2. ['product_id' => 'prod-100', 'name' => 'Desk'],
    3. ['product_id' => 'prod-200', 'name' => 'Chair'],
    4. ]);
    5. $plucked = $collection->pluck('name');
    6. $plucked->all();
    7. // ['Desk', 'Chair']

    你也可以通过传入第二个参数来指定生成集合的键:

    1. $plucked = $collection->pluck('name', 'product_id');
    2. $plucked->all();
    3. // ['prod-100' => 'Desk', 'prod-200' => 'Chair']

    如果存在重复的键,则最后一个匹配元素将被插入到弹出的集合中:

    1. $collection = collect([
    2. ['brand' => 'Tesla', 'color' => 'red'],
    3. ['brand' => 'Pagani', 'color' => 'white'],
    4. ['brand' => 'Tesla', 'color' => 'black'],
    5. ['brand' => 'Pagani', 'color' => 'orange'],
    6. ]);
    7. $plucked = $collection->pluck('color', 'brand');
    8. $plucked->all();
    9. // ['Tesla' => 'black', 'Pagani' => 'orange']

    pop()

    pop 方法从集合中移除并返回最后一个集合项:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $collection->pop();
    3. // 5
    4. $collection->all();
    5. // [1, 2, 3, 4]

    prepend()

    prepend 方法将指定的值添加的集合的开头:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $collection->prepend(0);
    3. $collection->all();
    4. // [0, 1, 2, 3, 4, 5]

    你也可以传递第二个参数来设置新增加集合项的键:

    1. $collection = collect(['one' => 1, 'two' => 2]);
    2. $collection->prepend(0, 'zero');
    3. $collection->all();
    4. // ['zero' => 0, 'one' => 1, 'two' => 2]

    pull()

    pull 方法把指定键对应的值从集合中移除并返回:

    1. $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
    2. $collection->pull('name');
    3. // 'Desk'
    4. $collection->all();
    5. // ['product_id' => 'prod-100']

    push()

    push 方法把指定的值追加到集合项的末尾:

    1. $collection = collect([1, 2, 3, 4]);
    2. $collection->push(5);
    3. $collection->all();
    4. // [1, 2, 3, 4, 5]

    put()

    put 方法在集合内设置给定的键值对:

    1. $collection = collect(['product_id' => 1, 'name' => 'Desk']);
    2. $collection->put('price', 100);
    3. $collection->all();
    4. // ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

    random()

    random 方法从集合中返回一个随机项:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $collection->random();
    3. // 4 - (retrieved randomly)

    你可以选择传入一个整数到 random 来指定要获取的随即项的数量。只要你显示传递你希望接收的数量时,则会返回项目的集合:

    1. $random = $collection->random(3);
    2. $random->all();
    3. // [2, 4, 5] - (retrieved randomly)

    如果集合的项小于指定的数量,则该方法将抛出 InvalidArgumentException

    reduce()

    reduce 方法将每次迭代的结果传递给下一次迭代直到集合减少为单个值:

    1. $collection = collect([1, 2, 3]);
    2. $total = $collection->reduce(function ($carry, $item) {
    3. return $carry + $item;
    4. });
    5. // 6

    第一次迭代时 $carry 的数值为 null; however,你也可以通过传入第二个参数到 reduce 来指定它的初始值:

    1. $collection->reduce(function ($carry, $item) {
    2. return $carry + $item;
    3. }, 4);
    4. // 10

    reject()

    reject 方法使用指定的回调函数过滤集合。如果回调函数返回 true 就会把对应的集合项从集合中移除:

    1. $collection = collect([1, 2, 3, 4]);
    2. $filtered = $collection->reject(function ($value, $key) {
    3. return $value > 2;
    4. });
    5. $filtered->all();
    6. // [1, 2]

    reject 方法对应的是 方法。

    reverse()

    reverse 方法用来倒转集合项的顺序,并保留原始的键:

    1. $collection = collect(['a', 'b', 'c', 'd', 'e']);
    2. $reversed = $collection->reverse();
    3. $reversed->all();
    4. /*
    5. [
    6. 4 => 'e',
    7. 3 => 'd',
    8. 2 => 'c',
    9. 1 => 'b',
    10. 0 => 'a',
    11. ]
    12. */

    search()

    search 方法在集合中搜索给定的值并返回它的键。如果没有找到,则返回 false

    使用 「宽松」的方式进行搜索,这意味着具有整数值的字符串会被认为等于相同值的整数。使用 「严格」的方式进行搜索,就传入 true 作为该方法的第二个参数:

    1. $collection->search('4', true);
    2. // false

    或者,你可以通过传递回调函数来搜索通过条件测试的第一个集合项:

    1. $collection->search(function ($item, $key) {
    2. return $item > 5;
    3. });
    4. // 2

    shift()

    shift 方法移除并返回集合的第一个集合项:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $collection->shift();
    3. // 1
    4. $collection->all();
    5. // [2, 3, 4, 5]

    shuffle()

    shuffle 方法随机打乱集合项:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $shuffled = $collection->shuffle();
    3. $shuffled->all();
    4. // [3, 2, 5, 1, 4] - (generated randomly)

    slice()

    slice 方法返回集合中给定索引开始后面的部分:

    1. $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    2. $slice = $collection->slice(4);
    3. $slice->all();
    4. // [5, 6, 7, 8, 9, 10]

    如果你想限制返回内容的大小,可以将你期望的大小作为第二个参数传递到该方法:

    1. $slice = $collection->slice(4, 2);
    2. $slice->all();
    3. // [5, 6]

    默认情况下,返回的内容将会保留原始键。如果你不希望保留原始键,你可以使用 values 方法来重新建立索引。

    some()

    方法的别名。

    sort()

    sort 方法对集合进行排序。排序后的集合会保留原数组的键,所以在这个例子我们将使用 方法去把键重置为连续编号的索引:

    1. $collection = collect([5, 3, 1, 2, 4]);
    2. $sorted = $collection->sort();
    3. // [1, 2, 3, 4, 5]

    如果你有更高级的排序需求,可以通过自己的算法将回调函数传递到 sort 。请参阅 PHP 文档的 uasort ,这是集合的 sort 方法在底层所调用的。

    Tip:如果你需要对嵌套数组或对象进行排序,请参照 和 sortByDesc 方法。

    sortBy()

    sortBy 方法将根据指定键对集合进行排序。排序后的集合会保留原始数组的键,所以在这个例子中我们使用 方法将键重置为连续编号的索引:

    1. $collection = collect([
    2. ['name' => 'Desk', 'price' => 200],
    3. ['name' => 'Chair', 'price' => 100],
    4. ['name' => 'Bookcase', 'price' => 150],
    5. ]);
    6. $sorted = $collection->sortBy('price');
    7. $sorted->values()->all();
    8. /*
    9. [
    10. ['name' => 'Chair', 'price' => 100],
    11. ['name' => 'Bookcase', 'price' => 150],
    12. ['name' => 'Desk', 'price' => 200],
    13. ]
    14. */

    你也可以传递你自己的回调函数用于决定如何对集合的值进行排序:

    1. $collection = collect([
    2. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    3. ['name' => 'Chair', 'colors' => ['Black']],
    4. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    5. ]);
    6. $sorted = $collection->sortBy(function ($product, $key) {
    7. return count($product['colors']);
    8. });
    9. $sorted->values()->all();
    10. /*
    11. [
    12. ['name' => 'Chair', 'colors' => ['Black']],
    13. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    14. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    15. ]
    16. */

    sortByDesc()

    该方法与 sortBy 方法一样,但是会以相反的顺序来对集合进行排序。

    sortKeys()

    sortKeys 方法通过底层关联数组的键来对集合进行排序:

    1. $collection = collect([
    2. 'id' => 22345,
    3. 'first' => 'John',
    4. 'last' => 'Doe',
    5. $sorted = $collection->sortKeys();
    6. $sorted->all();
    7. /*
    8. [
    9. 'first' => 'John',
    10. 'id' => 22345,
    11. 'last' => 'Doe',
    12. ]
    13. */

    sortKeysDesc()

    该方法与 方法一样,但是会以相反的顺序来对集合进行排序。

    splice()

    splice 方法移除并返回指定索引开始的集合项片段:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $chunk = $collection->splice(2);
    3. $chunk->all();
    4. // [3, 4, 5]
    5. $collection->all();
    6. // [1, 2]

    你可以传递第二个参数用以限制被删除内容的大小:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $chunk = $collection->splice(2, 1);
    3. $chunk->all();
    4. // [3]
    5. $collection->all();
    6. // [1, 2, 4, 5]

    此外,你可以传入含有新参数项的第三个参数来代替集合中删除的集合项:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $chunk = $collection->splice(2, 1, [10, 11]);
    3. $chunk->all();
    4. // [3]
    5. $collection->all();
    6. // [1, 2, 10, 11, 4, 5]

    split()

    split 方法将集合按照给定的值拆分:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $groups = $collection->split(3);
    3. $groups->toArray();
    4. // [[1, 2], [3, 4], [5]]

    sum()

    sum 方法返回集合内所有项的和:

    1. collect([1, 2, 3, 4, 5])->sum();
    2. // 15

    如果集合包含嵌套数组或对象,则应该传入一个键来指定要进行求和的值:

    1. $collection = collect([
    2. ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    3. ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
    4. ]);
    5. $collection->sum('pages');
    6. // 1272

    另外,你可以传入自己的回调函数来决定要用集合中的哪些值进行求和:

    1. $collection = collect([
    2. ['name' => 'Chair', 'colors' => ['Black']],
    3. ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    4. ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    5. ]);
    6. $collection->sum(function ($product) {
    7. return count($product['colors']);
    8. });
    9. // 6

    take()

    take 方法返回给定数量项的新集合:

    1. $collection = collect([0, 1, 2, 3, 4, 5]);
    2. $chunk = $collection->take(3);
    3. $chunk->all();
    4. // [0, 1, 2]

    你也可以传递负整数从集合末尾获取指定数量的项:

    1. $collection = collect([0, 1, 2, 3, 4, 5]);
    2. $chunk = $collection->take(-2);
    3. $chunk->all();
    4. // [4, 5]

    tap()

    tap 方法将给定的回调函数传入该集合,允许你在一个特定点「tap」集合,并在不影响集合本身的情况下对集合项执行某些操作:

    1. collect([2, 4, 3, 1, 5])
    2. ->sort()
    3. ->tap(function ($collection) {
    4. Log::debug('Values after sorting', $collection->values()->toArray());
    5. })
    6. ->shift();
    7. // 1

    times()

    静态 times 方法通过调用给定次数的回调函数来创建新集合:

    1. $collection = Collection::times(10, function ($number) {
    2. return $number * 9;
    3. });
    4. $collection->all();
    5. // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

    使用这个方法可以与工厂结合使用创建出 Eloquent 模型:

    1. $categories = Collection::times(3, function ($number) {
    2. return factory(Category::class)->create(['name' => "Category No. $number"]);
    3. });
    4. $categories->all();
    5. /*
    6. [
    7. ['id' => 1, 'name' => 'Category #1'],
    8. ['id' => 2, 'name' => 'Category #2'],
    9. ['id' => 3, 'name' => 'Category #3'],
    10. ]
    11. */

    toArray()

    toArray 方法将集合转换成 PHP 数组 。如果集合的值是 模型,那也会被转换成数组:

    1. $collection = collect(['name' => 'Desk', 'price' => 200]);
    2. $collection->toArray();
    3. /*
    4. [
    5. ['name' => 'Desk', 'price' => 200],
    6. ]
    7. */

    toJson()

    toJson 方法将集合转换成 JSON 字符串:

    1. $collection = collect(['name' => 'Desk', 'price' => 200]);
    2. $collection->toJson();
    3. // '{"name":"Desk", "price":200}'

    transform()

    transform 方法迭代集合并对每一个集合项调用给定的回调函数。而集合的内容也会被回调函数的返回值所取代:

    1. $collection = collect([1, 2, 3, 4, 5]);
    2. $collection->transform(function ($item, $key) {
    3. return $item * 2;
    4. });
    5. $collection->all();
    6. // [2, 4, 6, 8, 10]

    注意:与大多数集合方法不同, transform 会修改集合本身。如果你想创建新集合,可以使用 map 方法。

    union()

    union 方法将给定的数组添加到集合。如果给定的数组含有与原集合一样的键,则原集合的值不会被改变:

    1. $collection = collect([1 => ['a'], 2 => ['b']]);
    2. $union = $collection->union([3 => ['c'], 1 => ['b']]);
    3. $union->all();
    4. // [1 => ['a'], 2 => ['b'], 3 => ['c']]

    unique()

    unique 方法返回集合中所有唯一项。返回的集合保留着原数组的键,所以在这个例子中,我们使用 方法把键重置为连续编号的索引:

    1. $collection = collect([1, 1, 2, 2, 3, 4, 2]);
    2. $unique = $collection->unique();
    3. $unique->values()->all();
    4. // [1, 2, 3, 4]

    在处理嵌套数组或对象时,你可以指定用于确定唯一性的键:

    1. $collection = collect([
    2. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    3. ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    4. ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    5. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    6. ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    7. ]);
    8. $unique = $collection->unique('brand');
    9. $unique->values()->all();
    10. /*
    11. [
    12. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    13. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    14. ]
    15. */

    你也可以通过传递自己的回调函数来确定项的唯一性:

    1. $unique = $collection->unique(function ($item) {
    2. return $item['brand'].$item['type'];
    3. });
    4. $unique->values()->all();
    5. /*
    6. [
    7. ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    8. ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    9. ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    10. ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    11. ]
    12. */

    unique 方法在检查项目值时使用「宽松」模式比较,意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 uniqueStrict 方法做「严格」模式比较。

    uniqueStrict()

    这个方法与 方法一样,然而,所有的值是用 「严格」模式来比较的。

    unless()

    unless 方法当传入的第一个参数不为 true 的时候,将执行给定的回调函数:

    1. $collection = collect([1, 2, 3]);
    2. $collection->unless(true, function ($collection) {
    3. return $collection->push(4);
    4. });
    5. $collection->unless(false, function ($collection) {
    6. return $collection->push(5);
    7. });
    8. $collection->all();
    9. // [1, 2, 3, 5]

    unless 对应的是 when 方法。

    unlessEmpty()

    方法的别名。

    unlessNotEmpty()

    whenEmpty 方法的别名。

    unwrap()

    静态 unwrap 方法返回集合内部的可用值:

    1. Collection::unwrap(collect('John Doe'));
    2. // ['John Doe']
    3. Collection::unwrap(['John Doe']);
    4. // ['John Doe']
    5. Collection::unwrap('John Doe');
    6. // 'John Doe'

    values()

    values 方法返回键被重置为连续编号的新集合:

    1. $collection = collect([
    2. 10 => ['product' => 'Desk', 'price' => 200],
    3. 11 => ['product' => 'Desk', 'price' => 200]
    4. ]);
    5. $values = $collection->values();
    6. $values->all();
    7. /*
    8. [
    9. 0 => ['product' => 'Desk', 'price' => 200],
    10. 1 => ['product' => 'Desk', 'price' => 200],
    11. ]
    12. */

    when()

    when 方法当传入的第一个参数为 true 时,将执行给定的回调函数:

    1. $collection = collect([1, 2, 3]);
    2. $collection->when(true, function ($collection) {
    3. return $collection->push(4);
    4. });
    5. $collection->when(false, function ($collection) {
    6. return $collection->push(5);
    7. });
    8. $collection->all();
    9. // [1, 2, 3, 4]

    when 对应的是 方法。

    whenEmpty()

    whenEmpty 方法当集合为空时,将执行给定的回调函数:

    1. $collection = collect(['michael', 'tom']);
    2. $collection->whenEmpty(function ($collection) {
    3. return $collection->push('adam');
    4. });
    5. $collection->all();
    6. // ['michael', 'tom']
    7. $collection = collect();
    8. $collection->whenEmpty(function ($collection) {
    9. return $collection->push('adam');
    10. });
    11. $collection->all();
    12. // ['adam']
    13. $collection = collect(['michael', 'tom']);
    14. $collection->whenEmpty(function($collection) {
    15. return $collection->push('adam');
    16. }, function($collection) {
    17. return $collection->push('taylor');
    18. });
    19. $collection->all();
    20. // ['michael', 'tom', 'taylor']

    whenEmpty 对应的是 whenNotEmpty 方法。

    whenNotEmpty()

    whenNotEmpty 方法当集合不为空时,将执行给定的回调函数:

    1. $collection = collect(['michael', 'tom']);
    2. $collection->whenNotEmpty(function ($collection) {
    3. return $collection->push('adam');
    4. });
    5. $collection->all();
    6. // ['michael', 'tom', 'adam']
    7. $collection = collect();
    8. $collection->whenNotEmpty(function ($collection) {
    9. return $collection->push('adam');
    10. });
    11. $collection->all();
    12. // []
    13. $collection = collect();
    14. $collection->whenNotEmpty(function($collection) {
    15. return $collection->push('adam');
    16. }, function($collection) {
    17. return $collection->push('taylor');
    18. });
    19. $collection->all();
    20. // ['taylor']

    whenNotEmpty 对应的是 方法。

    where()

    where 方法通过给定的键 / 值对过滤集合:

    1. $collection = collect([
    2. ['product' => 'Desk', 'price' => 200],
    3. ['product' => 'Chair', 'price' => 100],
    4. ['product' => 'Bookcase', 'price' => 150],
    5. ['product' => 'Door', 'price' => 100],
    6. ]);
    7. $filtered = $collection->where('price', 100);
    8. $filtered->all();
    9. /*
    10. [
    11. ['product' => 'Chair', 'price' => 100],
    12. ['product' => 'Door', 'price' => 100],
    13. ]
    14. */

    where 方法在检查集合项值时使用「宽松」模式比较,这意味着具有整数值的字符串会被认为等于相同值的整数。你可以使用 whereStrict 方法进行「严格」模式比较。

    whereStrict()

    这个方法与 方法类似;不同的是会用「严格」的模式比较。

    whereBetween()

    whereBetween 方法会用给定的范围对集合进行过滤:

    1. $collection = collect([
    2. ['product' => 'Desk', 'price' => 200],
    3. ['product' => 'Chair', 'price' => 80],
    4. ['product' => 'Bookcase', 'price' => 150],
    5. ['product' => 'Pencil', 'price' => 30],
    6. ['product' => 'Door', 'price' => 100],
    7. ]);
    8. $filtered = $collection->whereBetween('price', [100, 200]);
    9. $filtered->all();
    10. /*
    11. [
    12. ['product' => 'Desk', 'price' => 200],
    13. ['product' => 'Bookcase', 'price' => 150],
    14. ['product' => 'Door', 'price' => 100],
    15. ]
    16. */

    whereIn()

    whereIn 会根据包含给定数组的键 / 值对来过滤集合:

    1. $collection = collect([
    2. ['product' => 'Desk', 'price' => 200],
    3. ['product' => 'Chair', 'price' => 100],
    4. ['product' => 'Bookcase', 'price' => 150],
    5. ['product' => 'Door', 'price' => 100],
    6. ]);
    7. $filtered = $collection->whereIn('price', [150, 200]);
    8. $filtered->all();
    9. /*
    10. [
    11. ['product' => 'Bookcase', 'price' => 150],
    12. ['product' => 'Desk', 'price' => 200],
    13. ]
    14. */

    whereIn 方法使用「宽松」的比较来检查集合项的值,这意味着具有整数值的字符串会被视为等于相同值的整数。你可以使用 whereInStrict 方法进行「严格」模式比较。

    whereInStrict()

    这个方法与 方法类似;不同的是会使用「严格」模式进行比较。

    whereInstanceOf()

    whereInstanceOf 方法根据指定的类来过滤集合:

    1. $collection = collect([
    2. new User,
    3. new User,
    4. new Post,
    5. ]);
    6. return $collection->whereInstanceOf(User::class);

    whereNotBetween()

    whereNotBetween 方法在指定的范围内过滤集合:

    1. $collection = collect([
    2. ['product' => 'Desk', 'price' => 200],
    3. ['product' => 'Chair', 'price' => 80],
    4. ['product' => 'Bookcase', 'price' => 150],
    5. ['product' => 'Pencil', 'price' => 30],
    6. ['product' => 'Door', 'price' => 100],
    7. ]);
    8. $filtered = $collection->whereNotBetween('price', [100, 200]);
    9. $filtered->all();
    10. /*
    11. [
    12. ['product' => 'Chair', 'price' => 80],
    13. ['product' => 'Pencil', 'price' => 30],
    14. ]
    15. */

    whereNotIn()

    whereNotIn 方法根据通过指定的键和不含有指定数组的值来对集合进行过滤:

    1. $collection = collect([
    2. ['product' => 'Desk', 'price' => 200],
    3. ['product' => 'Chair', 'price' => 100],
    4. ['product' => 'Bookcase', 'price' => 150],
    5. ['product' => 'Door', 'price' => 100],
    6. ]);
    7. $filtered = $collection->whereNotIn('price', [150, 200]);
    8. $filtered->all();
    9. /*
    10. [
    11. ['product' => 'Chair', 'price' => 100],
    12. ['product' => 'Door', 'price' => 100],
    13. ]
    14. */

    whereNotIn 方法使用「宽松」模式比较来检查集合项的值,这意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 whereNotInStrict 方法做 「严格」模式比较。

    whereNotInStrict()

    这个方法与 方法类似;不同的是会使用 「严格」模式作比较。

    wrap()

    静态 wrap 方法在适当的情况下将指定的值放在集合中:

    1. $collection = Collection::wrap('John Doe');
    2. $collection->all();
    3. // ['John Doe']
    4. $collection = Collection::wrap(['John Doe']);
    5. $collection->all();
    6. // ['John Doe']
    7. $collection = Collection::wrap(collect('John Doe'));
    8. $collection->all();
    9. // ['John Doe']

    zip()

    zip 方法将指定数组的值和相应索引的原集合的值合并在一起:

    1. $collection = collect(['Chair', 'Desk']);
    2. $zipped = $collection->zip([100, 200]);
    3. $zipped->all();
    4. // [['Chair', 100], ['Desk', 200]]

    集合也提供对「高阶消息传递」的支持,即集合常见操作的快捷方式。支持高阶消息传递的集合方法有: , avg, , each, , filter, , flatMap, , keyBy, , max, , partition, , some, , sortByDesc, , and unique

    每个高阶消息传递都能作为集合实例的动态的属性来访问。例如,使用 each 高阶消息传递在集合中的每个对象上调用一个方法:

    1. $users = User::where('votes', '>', 500)->get();
    2. $users->each->markAsVip();

    同样,我们可以使用 sum 高阶消息传递来收集 users 集合中的「投票」总数:

    本文章首发在 网站上。