Skip to content

集合

介绍

Illuminate\Support\Collection 类为处理数据数组提供了一个流畅、方便的包装。例如,查看以下代码。我们将使用 collect 辅助函数从数组创建一个新的集合实例,对每个元素运行 strtoupper 函数,然后移除所有空元素:

php
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
    return strtoupper($name);
})
->reject(function ($name) {
    return empty($name);
});

正如你所看到的,Collection 类允许你链式调用其方法以流畅地映射和减少底层数组。一般来说,集合是不可变的,这意味着每个 Collection 方法返回一个全新的 Collection 实例。

创建集合

如上所述,collect 辅助函数为给定数组返回一个新的 Illuminate\Support\Collection 实例。因此,创建一个集合就像这样简单:

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

Eloquent 查询的结果总是以 Collection 实例返回。

扩展集合

集合是“可宏化”的,这允许你在运行时向 Collection 类添加额外的方法。例如,以下代码向 Collection 类添加了一个 toUpper 方法:

php
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return Str::upper($value);
    });
});

$collection = collect(['first', 'second']);

$upper = $collection->toUpper();

// ['FIRST', 'SECOND']

通常,你应该在 服务提供者 中声明集合宏。

可用方法

在本文档的其余部分,我们将讨论 Collection 类上可用的每个方法。请记住,所有这些方法都可以链式调用以流畅地操作底层数组。此外,几乎每个方法都返回一个新的 Collection 实例,允许你在必要时保留集合的原始副本:

方法列表

all()

all 方法返回集合所代表的底层数组:

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

// [1, 2, 3]

average()

avg 方法的别名。

avg()

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

php
$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');

// 20

$average = collect([1, 1, 2, 4])->avg();

// 2

chunk()

chunk 方法将集合分解为多个较小的集合,每个集合的大小由给定的大小决定:

php
$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

此方法在使用诸如 Bootstrap 之类的网格系统时在视图中特别有用。想象一下你有一个 Eloquent 模型的集合,你想在网格中显示:

php
@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach

collapse()

collapse 方法将数组的集合折叠为一个单一的、平坦的集合:

php
$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

$collapsed = $collection->collapse();

$collapsed->all();

// [1, 2, 3, 4, 5, 6, 7, 8, 9]

combine()

combine 方法将集合的值作为键与另一个数组或集合的值组合:

php
$collection = collect(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]

collect()

collect 方法返回一个新的 Collection 实例,其中包含当前集合中的项目:

php
$collectionA = collect([1, 2, 3]);

$collectionB = $collectionA->collect();

$collectionB->all();

// [1, 2, 3]

collect 方法主要用于将惰性集合转换为标准 Collection 实例:

php
$lazyCollection = LazyCollection::make(function () {
    yield 1;
    yield 2;
    yield 3;
});

$collection = $lazyCollection->collect();

get_class($collection);

// 'Illuminate\Support\Collection'

$collection->all();

// [1, 2, 3]
lightbulb

当你有一个 Enumerable 实例并需要一个非惰性集合实例时,collect 方法特别有用。由于 collect()Enumerable 契约的一部分,你可以安全地使用它来获取 Collection 实例。

concat()

concat 方法将给定的 array 或集合值附加到集合的末尾:

php
$collection = collect(['John Doe']);

$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);

$concatenated->all();

// ['John Doe', 'Jane Doe', 'Johnny Doe']

contains()

contains 方法确定集合是否包含给定的项目:

php
$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');

// true

$collection->contains('New York');

// false

你还可以将键/值对传递给 contains 方法,这将确定给定的对是否存在于集合中:

php
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->contains('product', 'Bookcase');

// false

最后,你还可以将回调传递给 contains 方法以执行你自己的真值测试:

php
$collection = collect([1, 2, 3, 4, 5]);

$collection->contains(function ($value, $key) {
    return $value > 5;
});

// false

contains 方法在检查项目值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 containsStrict 方法以使用“严格”比较进行过滤。

containsStrict()

此方法与 contains 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。

lightbulb

使用 Eloquent Collections 时,此方法的行为会被修改。

count()

count 方法返回集合中的项目总数:

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

$collection->count();

// 4

countBy()

countBy 方法计算集合中值的出现次数。默认情况下,该方法计算每个元素的出现次数:

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

$counted = $collection->countBy();

$counted->all();

// [1 => 1, 2 => 3, 3 => 1]

然而,你可以将回调传递给 countBy 方法以按自定义值计算所有项目:

php
$collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);

$counted = $collection->countBy(function ($email) {
    return substr(strrchr($email, "@"), 1);
});

$counted->all();

// ['gmail.com' => 2, 'yahoo.com' => 1]

crossJoin()

crossJoin 方法在给定的数组或集合之间交叉连接集合的值,返回一个包含所有可能排列的笛卡尔积:

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

$matrix = $collection->crossJoin(['a', 'b']);

$matrix->all();

/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/

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

$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);

$matrix->all();

/*
    [
        [1, 'a', 'I'],
        [1, 'a', 'II'],
        [1, 'b', 'I'],
        [1, 'b', 'II'],
        [2, 'a', 'I'],
        [2, 'a', 'II'],
        [2, 'b', 'I'],
        [2, 'b', 'II'],
    ]
*/

dd()

dd 方法转储集合的项目并结束脚本的执行:

php
$collection = collect(['John Doe', 'Jane Doe']);

$collection->dd();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/

如果你不想停止执行脚本,请使用 dump 方法。

diff()

diff 方法根据其值将集合与另一个集合或纯 PHP array 进行比较。此方法将返回原始集合中不存在于给定集合中的值:

php
$collection = collect([1, 2, 3, 4, 5]);

$diff = $collection->diff([2, 4, 6, 8]);

$diff->all();

// [1, 3, 5]
lightbulb

使用 Eloquent Collections 时,此方法的行为会被修改。

diffAssoc()

diffAssoc 方法根据其键和值将集合与另一个集合或纯 PHP array 进行比较。此方法将返回原始集合中不存在于给定集合中的键/值对:

php
$collection = collect([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6
]);

$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6,
]);

$diff->all();

// ['color' => 'orange', 'remain' => 6]

diffKeys()

diffKeys 方法根据其键将集合与另一个集合或纯 PHP array 进行比较。此方法将返回原始集合中不存在于给定集合中的键/值对:

php
$collection = collect([
    'one' => 10,
    'two' => 20,
    'three' => 30,
    'four' => 40,
    'five' => 50,
]);

$diff = $collection->diffKeys([
    'two' => 2,
    'four' => 4,
    'six' => 6,
    'eight' => 8,
]);

$diff->all();

// ['one' => 10, 'three' => 30, 'five' => 50]

dump()

dump 方法转储集合的项目:

php
$collection = collect(['John Doe', 'Jane Doe']);

$collection->dump();

/*
    Collection {
        #items: array:2 [
            0 => "John Doe"
            1 => "Jane Doe"
        ]
    }
*/

如果你想在转储集合后停止执行脚本,请使用 dd 方法。

duplicates()

duplicates 方法从集合中检索并返回重复值:

php
$collection = collect(['a', 'b', 'a', 'c', 'b']);

$collection->duplicates();

// [2 => 'a', 4 => 'b']

如果集合包含数组或对象,你可以传递要检查重复值的属性的键:

php
$employees = collect([
    ['email' => 'abigail@example.com', 'position' => 'Developer'],
    ['email' => 'james@example.com', 'position' => 'Designer'],
    ['email' => 'victoria@example.com', 'position' => 'Developer'],
])

$employees->duplicates('position');

// [2 => 'Developer']

duplicatesStrict()

此方法与 duplicates 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。

each()

each 方法遍历集合中的项目并将每个项目传递给回调:

php
$collection->each(function ($item, $key) {
    //
});

如果你想停止遍历项目,你可以从回调中返回 false

php
$collection->each(function ($item, $key) {
    if (/* some condition */) {
        return false;
    }
});

eachSpread()

eachSpread 方法遍历集合的项目,将每个嵌套项目值传递给给定的回调:

php
$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);

$collection->eachSpread(function ($name, $age) {
    //
});

你可以通过从回调中返回 false 来停止遍历项目:

php
$collection->eachSpread(function ($name, $age) {
    return false;
});

every()

every 方法可用于验证集合的所有元素是否通过给定的真值测试:

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

// false

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

php
$collection = collect([]);

$collection->every(function ($value, $key) {
    return $value > 2;
});

// true

except()

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

php
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);

$filtered = $collection->except(['price', 'discount']);

$filtered->all();

// ['product_id' => 1]

有关 except 的反向操作,请参阅 only 方法。

lightbulb

使用 Eloquent Collections 时,此方法的行为会被修改。

filter()

filter 方法使用给定的回调过滤集合,仅保留通过给定真值测试的项目:

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

$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [3, 4]

如果没有提供回调,所有等价于 false 的集合条目将被移除:

php
$collection = collect([1, 2, 3, null, false, '', 0, []]);

$collection->filter()->all();

// [1, 2, 3]

有关 filter 的反向操作,请参阅 reject 方法。

first()

first 方法返回集合中通过给定真值测试的第一个元素:

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

// 3

你还可以在没有参数的情况下调用 first 方法以获取集合中的第一个元素。如果集合为空,则返回 null

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

// 1

firstWhere()

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

php
$collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
]);

$collection->firstWhere('name', 'Linda');

// ['name' => 'Linda', 'age' => 14]

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

php
$collection->firstWhere('age', '>=', 18);

// ['name' => 'Diego', 'age' => 23]

where 方法一样,你可以将一个参数传递给 firstWhere 方法。在这种情况下,firstWhere 方法将返回第一个项目,其中给定项目键的值为“真”:

php
$collection->firstWhere('age');

// ['name' => 'Linda', 'age' => 14]

flatMap()

flatMap 方法遍历集合并将每个值传递给给定的回调。回调可以自由修改项目并返回它,从而形成一个新的修改项目集合。然后,数组被扁平化为一个级别:

php
$collection = collect([
    ['name' => 'Sally'],
    ['school' => 'Arkansas'],
    ['age' => 28]
]);

$flattened = $collection->flatMap(function ($values) {
    return array_map('strtoupper', $values);
});

$flattened->all();

// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];

flatten()

flatten 方法将多维集合扁平化为单一维度:

php
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);

$flattened = $collection->flatten();

$flattened->all();

// ['taylor', 'php', 'javascript'];

你可以选择性地传递一个“深度”参数:

php
$collection = collect([
    'Apple' => [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    ],
    'Samsung' => [
        ['name' => 'Galaxy S7', 'brand' => 'Samsung']
    ],
]);

$products = $collection->flatten(1);

$products->values()->all();

/*
    [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
        ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
    ]
*/

在此示例中,如果不提供深度调用 flatten,则还会扁平化嵌套数组,结果为 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']。提供深度允许你限制将被扁平化的嵌套数组的级别。

flip()

flip 方法将集合的键与其对应的值交换:

php
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$flipped = $collection->flip();

$flipped->all();

// ['taylor' => 'name', 'laravel' => 'framework']

forget()

forget 方法通过其键从集合中移除一个项目:

php
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$collection->forget('name');

$collection->all();

// ['framework' => 'laravel']
exclamation

与大多数其他集合方法不同,forget 不返回一个新的修改集合;它修改被调用的集合。

forPage()

forPage 方法返回一个新集合,其中包含将在给定页码上显示的项目。该方法接受页码作为第一个参数,每页显示的项目数作为第二个参数:

php
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();

// [4, 5, 6]

get()

get 方法返回给定键的项目。如果键不存在,则返回 null

php
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$value = $collection->get('name');

// taylor

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

php
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$value = $collection->get('foo', 'default-value');

// default-value

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

php
$collection->get('email', function () {
    return 'default-value';
});

// default-value

groupBy()

groupBy 方法按给定键对集合的项目进行分组:

php
$collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

你可以传递一个回调而不是字符串 key。回调应返回你希望用来键控分组的值:

php
$grouped = $collection->groupBy(function ($item, $key) {
    return substr($item['account_id'], -3);
});

$grouped->toArray();

/*
    [
        'x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

可以将多个分组标准作为数组传递。每个数组元素将应用于多维数组中的相应级别:

php
$data = new Collection([
    10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
    20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
    30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
    40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
]);

$result = $data->groupBy([
    'skill',
    function ($item) {
        return $item['roles'];
    },
], $preserveKeys = true);

/*
[
    1 => [
        'Role_1' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_2' => [
            20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
        ],
        'Role_3' => [
            10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
        ],
    ],
    2 => [
        'Role_1' => [
            30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
        ],
        'Role_2' => [
            40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
        ],
    ],
];
*/

has()

has 方法确定集合中是否存在给定键:

php
$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);

$collection->has('product');

// true

$collection->has(['product', 'amount']);

// true

$collection->has(['amount', 'price']);

// false

implode()

implode 方法连接集合中的项目。其参数取决于集合中项目的类型。如果集合包含数组或对象,你应该传递你希望连接的属性的键,以及你希望在值之间放置的“粘合”字符串:

php
$collection = collect([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
]);

$collection->implode('product', ', ');

// Desk, Chair

如果集合包含简单的字符串或数值,请将“粘合”作为方法的唯一参数传递:

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

// '1-2-3-4-5'

intersect()

intersect 方法从原始集合中移除不在给定 array 或集合中的任何值。结果集合将保留原始集合的键:

php
$collection = collect(['Desk', 'Sofa', 'Chair']);

$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

$intersect->all();

// [0 => 'Desk', 2 => 'Chair']
lightbulb

使用 Eloquent Collections 时,此方法的行为会被修改。

intersectByKeys()

intersectByKeys 方法从原始集合中移除不在给定 array 或集合中的任何键:

php
$collection = collect([
    'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
]);

$intersect = $collection->intersectByKeys([
    'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
]);

$intersect->all();

// ['type' => 'screen', 'year' => 2009]

isEmpty()

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

php
collect([])->isEmpty();

// true

isNotEmpty()

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

php
collect([])->isNotEmpty();

// false

join()

join 方法使用字符串连接集合的值:

php
collect(['a', 'b', 'c'])->join(', '); // 'a, b, c'
collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
collect(['a', 'b'])->join(', ', ' and '); // 'a and b'
collect(['a'])->join(', ', ' and '); // 'a'
collect([])->join(', ', ' and '); // ''

keyBy()

keyBy 方法通过给定键对集合进行键控。如果多个项目具有相同的键,则只有最后一个会出现在新集合中:

php
$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$keyed = $collection->keyBy('product_id');

$keyed->all();

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

你还可以将回调传递给方法。回调应返回用于键控集合的值:

php
$keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
});

$keyed->all();

/*
    [
        'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

keys()

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

php
$collection = collect([
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$keys = $collection->keys();

$keys->all();

// ['prod-100', 'prod-200']

last()

last 方法返回集合中通过给定真值测试的最后一个元素:

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

// 2

你还可以在没有参数的情况下调用 last 方法以获取集合中的最后一个元素。如果集合为空,则返回 null

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

// 4

macro()

静态 macro 方法允许你在运行时向 Collection 类添加方法。有关更多信息,请参阅扩展集合的文档。

make()

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

map()

map 方法遍历集合并将每个值传递给给定的回调。回调可以自由修改项目并返回它,从而形成一个新的修改项目集合:

php
$collection = collect([1, 2, 3, 4, 5]);

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]
exclamation

像大多数其他集合方法一样,map 返回一个新的集合实例;它不会修改被调用的集合。如果你想转换原始集合,请使用 transform 方法。

mapInto()

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

php
class Currency
{
    /**
     * 创建一个新的货币实例。
     *
     * @param  string  $code
     * @return void
     */
    function __construct(string $code)
    {
        $this->code = $code;
    }
}

$collection = collect(['USD', 'EUR', 'GBP']);

$currencies = $collection->mapInto(Currency::class);

$currencies->all();

// [Currency('USD'), Currency('EUR'), Currency('GBP')]

mapSpread()

mapSpread 方法遍历集合的项目,将每个嵌套项目值传递给给定的回调。回调可以自由修改项目并返回它,从而形成一个新的修改项目集合:

php
$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunks = $collection->chunk(2);

$sequence = $chunks->mapSpread(function ($even, $odd) {
    return $even + $odd;
});

$sequence->all();

// [1, 5, 9, 13, 17]

mapToGroups()

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

php
$collection = collect([
    [
        'name' => 'John Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Jane Doe',
        'department' => 'Sales',
    ],
    [
        'name' => 'Johnny Doe',
        'department' => 'Marketing',
    ]
]);

$grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
});

$grouped->toArray();

/*
    [
        'Sales' => ['John Doe', 'Jane Doe'],
        'Marketing' => ['Johnny Doe'],
    ]
*/

$grouped->get('Sales')->all();

// ['John Doe', 'Jane Doe']

mapWithKeys()

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

php
$collection = collect([
    [
        'name' => 'John',
        'department' => 'Sales',
        'email' => 'john@example.com'
    ],
    [
        'name' => 'Jane',
        'department' => 'Marketing',
        'email' => 'jane@example.com'
    ]
]);

$keyed = $collection->mapWithKeys(function ($item) {
    return [$item['email'] => $item['name']];
});

$keyed->all();

/*
    [
        'john@example.com' => 'John',
        'jane@example.com' => 'Jane',
    ]
*/

max()

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

php
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');

// 20

$max = collect([1, 2, 3, 4, 5])->max();

// 5

median()

median 方法返回给定键的中位数值

php
$median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');

// 15

$median = collect([1, 1, 2, 4])->median();

// 1.5

merge()

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

php
$collection = collect(['product_id' => 1, 'price' => 100]);

$merged = $collection->merge(['price' => 200, 'discount' => false]);

$merged->all();

// ['product_id' => 1, 'price' => 200, 'discount' => false]

如果给定项目的键是数字,则值将附加到集合的末尾:

php
$collection = collect(['Desk', 'Chair']);

$merged = $collection->merge(['Bookcase', 'Door']);

$merged->all();

// ['Desk', 'Chair', 'Bookcase', 'Door']

mergeRecursive()

mergeRecursive 方法递归地将给定的数组或集合与原始集合合并。如果给定项目中的字符串键与原始集合中的字符串键匹配,则这些键的值将合并为一个数组,并且这是递归进行的:

php
$collection = collect(['product_id' => 1, 'price' => 100]);

$merged = $collection->mergeRecursive(['product_id' => 2, 'price' => 200, 'discount' => false]);

$merged->all();

// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]

min()

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

php
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');

// 10

$min = collect([1, 2, 3, 4, 5])->min();

// 1

mode()

mode 方法返回给定键的众数值

php
$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');

// [10]

$mode = collect([1, 1, 2, 4])->mode();

// [1]

nth()

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

php
$collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

$collection->nth(4);

// ['a', 'e']

你可以选择性地传递一个偏移量作为第二个参数:

php
$collection->nth(4, 1);

// ['b', 'f']

only()

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

php
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']

有关 only 的反向操作,请参阅 except 方法。

lightbulb

使用 Eloquent Collections 时,此方法的行为会被修改。

pad()

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

要向左填充,你应该指定一个负大小。如果给定大小的绝对值小于或等于数组的长度,则不会进行填充:

php
$collection = collect(['A', 'B', 'C']);

$filtered = $collection->pad(5, 0);

$filtered->all();

// ['A', 'B', 'C', 0, 0]

$filtered = $collection->pad(-5, 0);

$filtered->all();

// [0, 0, 'A', 'B', 'C']

partition()

partition 方法可以与 list PHP 函数结合使用,以将通过给定真值测试的元素与未通过的元素分开:

php
$collection = collect([1, 2, 3, 4, 5, 6]);

list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) {
    return $i < 3;
});

$underThree->all();

// [1, 2]

$equalOrAboveThree->all();

// [3, 4, 5, 6]

pipe()

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

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

$piped = $collection->pipe(function ($collection) {
    return $collection->sum();
});

// 6

pluck()

pluck 方法用于检索给定键的所有值:

php
$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

$plucked = $collection->pluck('name');

$plucked->all();

// ['Desk', 'Chair']

你还可以指定结果集合的键:

php
$plucked = $collection->pluck('name', 'product_id');

$plucked->all();

// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

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

php
$collection = collect([
    ['brand' => 'Tesla',  'color' => 'red'],
    ['brand' => 'Pagani', 'color' => 'white'],
    ['brand' => 'Tesla',  'color' => 'black'],
    ['brand' => 'Pagani', 'color' => 'orange'],
]);

$plucked = $collection->pluck('color', 'brand');

$plucked->all();

// ['Tesla' => 'black', 'Pagani' => 'orange']

pop()

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

php
$collection = collect([1, 2, 3, 4, 5]);

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]

prepend()

prepend 方法将一个项目添加到集合的开头:

php
$collection = collect([1, 2, 3, 4, 5]);

$collection->prepend(0);

$collection->all();

// [0, 1, 2, 3, 4, 5]

你还可以传递第二个参数来设置预置项目的键:

php
$collection = collect(['one' => 1, 'two' => 2]);

$collection->prepend(0, 'zero');

$collection->all();

// ['zero' => 0, 'one' => 1, 'two' => 2]

pull()

pull 方法通过键移除并返回集合中的一项:

php
$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);

$collection->pull('name');

// 'Desk'

$collection->all();

// ['product_id' => 'prod-100']

push()

push 方法将一个项目追加到集合的末尾:

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

$collection->push(5);

$collection->all();

// [1, 2, 3, 4, 5]

put()

put 方法在集合中设置给定的键和值:

php
$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

random()

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

php
$collection = collect([1, 2, 3, 4, 5]);

$collection->random();

// 4 - (随机检索)

你可以选择传递一个整数给 random 来指定你想随机检索多少项。当明确传递你希望接收的项数时,总是返回一个项的集合:

php
$random = $collection->random(3);

$random->all();

// [2, 4, 5] - (随机检索)

如果集合中的项少于请求的数量,该方法将抛出 InvalidArgumentException

reduce()

reduce 方法将集合减少为一个值,将每次迭代的结果传递到后续迭代中:

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

$total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
});

// 6

第一次迭代时 $carry 的值为 null;然而,你可以通过传递第二个参数给 reduce 来指定其初始值:

php
$collection->reduce(function ($carry, $item) {
    return $carry + $item;
}, 4);

// 10

reject()

reject 方法使用给定的回调过滤集合。如果回调返回 true,则该项将从结果集合中移除:

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

$filtered = $collection->reject(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [1, 2]

reject 方法的反义词是 filter 方法。

replace()

replace 方法的行为类似于 merge;然而,除了覆盖具有字符串键的匹配项外,replace 方法还将覆盖集合中具有匹配数字键的项:

php
$collection = collect(['Taylor', 'Abigail', 'James']);

$replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);

$replaced->all();

// ['Taylor', 'Victoria', 'James', 'Finn']

replaceRecursive()

此方法的工作方式类似于 replace,但它将递归到数组中并对内部值应用相同的替换过程:

php
$collection = collect(['Taylor', 'Abigail', ['James', 'Victoria', 'Finn']]);

$replaced = $collection->replaceRecursive(['Charlie', 2 => [1 => 'King']]);

$replaced->all();

// ['Charlie', 'Abigail', ['James', 'King', 'Finn']]

reverse()

reverse 方法反转集合项的顺序,保留原始键:

php
$collection = collect(['a', 'b', 'c', 'd', 'e']);

$reversed = $collection->reverse();

$reversed->all();

/*
    [
        4 => 'e',
        3 => 'd',
        2 => 'c',
        1 => 'b',
        0 => 'a',
    ]
*/

search 方法在集合中搜索给定值并返回其键(如果找到)。如果未找到该项,则返回 false

php
$collection = collect([2, 4, 6, 8]);

$collection->search(4);

// 1

搜索是使用“宽松”比较进行的,这意味着具有整数值的字符串将被视为与相同值的整数相等。要使用“严格”比较,请将 true 作为第二个参数传递给该方法:

php
$collection->search('4', true);

// false

或者,你可以传入自己的回调来搜索通过你的真值测试的第一个项:

php
$collection->search(function ($item, $key) {
    return $item > 5;
});

// 2

shift()

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

php
$collection = collect([1, 2, 3, 4, 5]);

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]

shuffle()

shuffle 方法随机打乱集合中的项:

php
$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (随机生成)

skip()

skip 方法返回一个新集合,不包含前给定数量的项:

php
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$collection = $collection->skip(4);

$collection->all();

// [5, 6, 7, 8, 9, 10]

slice()

slice 方法返回从给定索引开始的集合切片:

php
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$slice = $collection->slice(4);

$slice->all();

// [5, 6, 7, 8, 9, 10]

如果你想限制返回切片的大小,请将所需的大小作为第二个参数传递给该方法:

php
$slice = $collection->slice(4, 2);

$slice->all();

// [5, 6]

返回的切片默认会保留键。如果你不希望保留原始键,可以使用 values 方法重新索引它们。

some()

some 方法是 contains 方法的别名。

sort()

sort 方法对集合进行排序。排序后的集合保留原始数组键,因此在此示例中我们将使用 values 方法将键重置为连续编号的索引:

php
$collection = collect([5, 3, 1, 2, 4]);

$sorted = $collection->sort();

$sorted->values()->all();

// [1, 2, 3, 4, 5]

如果你的排序需求更复杂,你可以传递一个回调给 sort,使用你自己的算法。请参考 PHP 文档中的 uasort,这是集合的 sort 方法在底层调用的。

lightbulb

如果你需要对嵌套数组或对象的集合进行排序,请参阅 sortBysortByDesc 方法。

sortBy()

sortBy 方法按给定键对集合进行排序。排序后的集合保留原始数组键,因此在此示例中我们将使用 values 方法将键重置为连续编号的索引:

php
$collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy('price');

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'price' => 100],
        ['name' => 'Bookcase', 'price' => 150],
        ['name' => 'Desk', 'price' => 200],
    ]
*/

你还可以传递自己的回调来确定如何对集合值进行排序:

php
$collection = collect([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$sorted = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
});

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
*/

sortByDesc()

此方法与 sortBy 方法具有相同的签名,但会以相反的顺序对集合进行排序。

sortKeys()

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

php
$collection = collect([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);

$sorted = $collection->sortKeys();

$sorted->all();

/*
    [
        'first' => 'John',
        'id' => 22345,
        'last' => 'Doe',
    ]
*/

sortKeysDesc()

此方法与 sortKeys 方法具有相同的签名,但会以相反的顺序对集合进行排序。

splice()

splice 方法移除并返回从指定索引开始的项的切片:

php
$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2);

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]

你可以传递第二个参数来限制结果块的大小:

php
$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2, 1);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]

此外,你可以传递第三个参数,包含要替换从集合中移除的项的新项:

php
$collection = collect([1, 2, 3, 4, 5]);

$chunk = $collection->splice(2, 1, [10, 11]);

$chunk->all();

// [3]

$collection->all();

// [1, 2, 10, 11, 4, 5]

split()

split 方法将集合分成给定数量的组:

php
$collection = collect([1, 2, 3, 4, 5]);

$groups = $collection->split(3);

$groups->toArray();

// [[1, 2], [3, 4], [5]]

sum()

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

php
collect([1, 2, 3, 4, 5])->sum();

// 15

如果集合包含嵌套数组或对象,你应该传递一个键来用于确定要求和的值:

php
$collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);

$collection->sum('pages');

// 1272

此外,你可以传递自己的回调来确定集合中要求和的值:

php
$collection = collect([
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$collection->sum(function ($product) {
    return count($product['colors']);
});

// 6

take()

take 方法返回一个包含指定数量项的新集合:

php
$collection = collect([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]

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

php
$collection = collect([0, 1, 2, 3, 4, 5]);

$chunk = $collection->take(-2);

$chunk->all();

// [4, 5]

tap()

tap 方法将集合传递给给定的回调,允许你在特定点“插入”集合并对项进行操作,而不影响集合本身:

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

// 1

times()

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

php
$collection = Collection::times(10, function ($number) {
    return $number * 9;
});

$collection->all();

// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

此方法在与工厂结合使用以创建 Eloquent 模型时非常有用:

php
$categories = Collection::times(3, function ($number) {
    return factory(Category::class)->create(['name' => "Category No. $number"]);
});

$categories->all();

/*
    [
        ['id' => 1, 'name' => 'Category No. 1'],
        ['id' => 2, 'name' => 'Category No. 2'],
        ['id' => 3, 'name' => 'Category No. 3'],
    ]
*/

toArray()

toArray 方法将集合转换为普通的 PHP array。如果集合的值是 Eloquent 模型,模型也将被转换为数组:

php
$collection = collect(['name' => 'Desk', 'price' => 200]);

$collection->toArray();

/*
    [
        ['name' => 'Desk', 'price' => 200],
    ]
*/
exclamation

toArray 还会将集合中所有实现 Arrayable 的嵌套对象转换为数组。如果你想获取原始的底层数组,请使用 all 方法。

toJson()

toJson 方法将集合转换为 JSON 序列化字符串:

php
$collection = collect(['name' => 'Desk', 'price' => 200]);

$collection->toJson();

// '{"name":"Desk", "price":200}'

transform()

transform 方法遍历集合并对集合中的每个项调用给定的回调。集合中的项将被回调返回的值替换:

php
$collection = collect([1, 2, 3, 4, 5]);

$collection->transform(function ($item, $key) {
    return $item * 2;
});

$collection->all();

// [2, 4, 6, 8, 10]
exclamation

与大多数其他集合方法不同,transform 会修改集合本身。如果你希望创建一个新集合,请使用 map 方法。

union()

union 方法将给定数组添加到集合中。如果给定数组包含已经在原始集合中的键,则原始集合的值将被优先:

php
$collection = collect([1 => ['a'], 2 => ['b']]);

$union = $collection->union([3 => ['c'], 1 => ['b']]);

$union->all();

// [1 => ['a'], 2 => ['b'], 3 => ['c']]

unique()

unique 方法返回集合中所有唯一的项。返回的集合保留原始数组键,因此在此示例中我们将使用 values 方法将键重置为连续编号的索引:

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

$unique = $collection->unique();

$unique->values()->all();

// [1, 2, 3, 4]

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

php
$collection = collect([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);

$unique = $collection->unique('brand');

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
*/

你还可以传递自己的回调来确定项的唯一性:

php
$unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
});

$unique->values()->all();

/*
    [
        ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
        ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
        ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
*/

unique 方法在检查项值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 uniqueStrict 方法以“严格”比较进行过滤。

lightbulb

使用 Eloquent Collections 时,此方法的行为会有所不同。

uniqueStrict()

此方法与 unique 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。

unless()

unless 方法将在传递给方法的第一个参数计算为 true 时执行给定的回调:

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

$collection->unless(true, function ($collection) {
    return $collection->push(4);
});

$collection->unless(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 5]

unless 的反义词是 when 方法。

unlessEmpty()

unlessEmpty 方法是 whenNotEmpty 方法的别名。

unlessNotEmpty()

unlessNotEmpty 方法是 whenEmpty 方法的别名。

unwrap()

静态 unwrap 方法返回给定值的集合的底层项(如果适用):

php
Collection::unwrap(collect('John Doe'));

// ['John Doe']

Collection::unwrap(['John Doe']);

// ['John Doe']

Collection::unwrap('John Doe');

// 'John Doe'

values()

values 方法返回一个新集合,键重置为连续整数:

php
$collection = collect([
    10 => ['product' => 'Desk', 'price' => 200],
    11 => ['product' => 'Desk', 'price' => 200]
]);

$values = $collection->values();

$values->all();

/*
    [
        0 => ['product' => 'Desk', 'price' => 200],
        1 => ['product' => 'Desk', 'price' => 200],
    ]
*/

when()

when 方法将在传递给方法的第一个参数计算为 true 时执行给定的回调:

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

$collection->when(true, function ($collection) {
    return $collection->push(4);
});

$collection->when(false, function ($collection) {
    return $collection->push(5);
});

$collection->all();

// [1, 2, 3, 4]

when 的反义词是 unless 方法。

whenEmpty()

whenEmpty 方法将在集合为空时执行给定的回调:

php
$collection = collect(['michael', 'tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// ['michael', 'tom']

$collection = collect();

$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// ['adam']

$collection = collect(['michael', 'tom']);

$collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
}, function ($collection) {
    return $collection->push('taylor');
});

$collection->all();

// ['michael', 'tom', 'taylor']

whenEmpty 的反义词是 whenNotEmpty 方法。

whenNotEmpty()

whenNotEmpty 方法将在集合不为空时执行给定的回调:

php
$collection = collect(['michael', 'tom']);

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// ['michael', 'tom', 'adam']

$collection = collect();

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
});

$collection->all();

// []

$collection = collect();

$collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
}, function ($collection) {
    return $collection->push('taylor');
});

$collection->all();

// ['taylor']

whenNotEmpty 的反义词是 whenEmpty 方法。

where()

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

php
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

where 方法在检查项值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 whereStrict 方法以“严格”比较进行过滤。

可选地,你可以将比较运算符作为第二个参数传递。

php
$collection = collect([
    ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
    ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ['name' => 'Sue', 'deleted_at' => null],
]);

$filtered = $collection->where('deleted_at', '!=', null);

$filtered->all();

/*
    [
        ['name' => 'Jim', 'deleted_at' => '2019-01-01 00:00:00'],
        ['name' => 'Sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ]
*/

whereStrict()

此方法与 where 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。

whereBetween()

whereBetween 方法在给定范围内过滤集合:

php
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereBetween('price', [100, 200]);

$filtered->all();

/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
    ]
*/

whereIn()

whereIn 方法通过给定数组中包含的键/值对过滤集合:

php
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Bookcase', 'price' => 150],
    ]
*/

whereIn 方法在检查项值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 whereInStrict 方法以“严格”比较进行过滤。

whereInStrict()

此方法与 whereIn 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。

whereInstanceOf()

whereInstanceOf 方法通过给定的类类型过滤集合:

php
use App\User;
use App\Post;

$collection = collect([
    new User,
    new User,
    new Post,
]);

$filtered = $collection->whereInstanceOf(User::class);

$filtered->all();

// [App\User, App\User]

whereNotBetween()

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

php
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereNotBetween('price', [100, 200]);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 80],
        ['product' => 'Pencil', 'price' => 30],
    ]
*/

whereNotIn()

whereNotIn 方法通过给定数组中不包含的键/值对过滤集合:

php
$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->whereNotIn('price', [150, 200]);

$filtered->all();

/*
    [
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Door', 'price' => 100],
    ]
*/

whereNotIn 方法在检查项值时使用“宽松”比较,这意味着具有整数值的字符串将被视为与相同值的整数相等。使用 whereNotInStrict 方法以“严格”比较进行过滤。

whereNotInStrict()

此方法与 whereNotIn 方法具有相同的签名;然而,所有值都使用“严格”比较进行比较。

whereNotNull()

whereNotNull 方法过滤给定键不为 null 的项:

php
$collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNotNull('name');

$filtered->all();

/*
    [
        ['name' => 'Desk'],
        ['name' => 'Bookcase'],
    ]
*/

whereNull()

whereNull 方法过滤给定键为 null 的项:

php
$collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
]);

$filtered = $collection->whereNull('name');

$filtered->all();

/*
    [
        ['name' => null],
    ]
*/

wrap()

静态 wrap 方法在适用时将给定值包装在集合中:

php
$collection = Collection::wrap('John Doe');

$collection->all();

// ['John Doe']

$collection = Collection::wrap(['John Doe']);

$collection->all();

// ['John Doe']

$collection = Collection::wrap(collect('John Doe'));

$collection->all();

// ['John Doe']

zip()

zip 方法将给定数组的值与原始集合中对应索引的值合并在一起:

php
$collection = collect(['Chair', 'Desk']);

$zipped = $collection->zip([100, 200]);

$zipped->all();

// [['Chair', 100], ['Desk', 200]]

高阶消息

集合还支持“高阶消息”,这是在集合上执行常见操作的快捷方式。提供高阶消息的集合方法有:averageavgcontainseacheveryfilterfirstflatMapgroupBykeyBymapmaxminpartitionrejectsomesortBysortByDescsumunique

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

php
$users = User::where('votes', '>', 500)->get();

$users->each->markAsVip();

同样,我们可以使用 sum 高阶消息来收集用户集合的“投票”总数:

php
$users = User::where('group', 'Development')->get();

return $users->sum->votes;

惰性集合

介绍

exclamation

在深入了解 Laravel 的惰性集合之前,请花一些时间熟悉 PHP 生成器

为了补充已经强大的 Collection 类,LazyCollection 类利用 PHP 的 生成器 允许你在保持低内存使用的同时处理非常大的数据集。

例如,假设你的应用程序需要处理一个多千兆字节的日志文件,同时利用 Laravel 的集合方法来解析日志。与其一次性将整个文件读入内存,不如使用惰性集合来在给定时间内仅将文件的一小部分保留在内存中:

php
use App\LogEntry;
use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
    $handle = fopen('log.txt', 'r');

    while (($line = fgets($handle)) !== false) {
        yield $line;
    }
})->chunk(4)->map(function ($lines) {
    return LogEntry::fromLines($lines);
})->each(function (LogEntry $logEntry) {
    // 处理日志条目...
});

或者,假设你需要遍历 10,000 个 Eloquent 模型。使用传统的 Laravel 集合时,所有 10,000 个 Eloquent 模型必须同时加载到内存中:

php
$users = App\User::all()->filter(function ($user) {
    return $user->id > 500;
});

然而,查询构建器的 cursor 方法返回一个 LazyCollection 实例。这允许你仍然只对数据库运行一个查询,但也只在内存中保留一个 Eloquent 模型。在此示例中,filter 回调在我们实际逐个迭代每个用户之前不会执行,从而大大减少了内存使用:

php
$users = App\User::cursor()->filter(function ($user) {
    return $user->id > 500;
});

foreach ($users as $user) {
    echo $user->id;
}

创建惰性集合

要创建惰性集合实例,你应该将 PHP 生成器函数传递给集合的 make 方法:

php
use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
    $handle = fopen('log.txt', 'r');

    while (($line = fgets($handle)) !== false) {
        yield $line;
    }
});

可枚举契约

Collection 类上几乎所有可用的方法在 LazyCollection 类上也可用。这两个类都实现了 Illuminate\Support\Enumerable 契约,该契约定义了以下方法:

exclamation

修改集合的方法(如 shiftpopprepend 等)在 LazyCollection 类上不可用。

惰性集合方法

除了 Enumerable 契约中定义的方法外,LazyCollection 类还包含以下方法:

tapEach()

虽然 each 方法立即为集合中的每个项调用给定的回调,但 tapEach 方法仅在从列表中逐个拉出项时调用给定的回调:

php
$lazyCollection = LazyCollection::times(INF)->tapEach(function ($value) {
    dump($value);
});

// 到目前为止还没有输出...

$array = $lazyCollection->take(3)->all();

// 1
// 2
// 3

remember()

remember 方法返回一个新的惰性集合,该集合将记住已枚举的任何值,并在集合再次枚举时不会再次检索它们:

php
$users = User::cursor()->remember();

// 尚未执行查询...

$users->take(5)->all();

// 查询已执行,前 5 个用户已从数据库中加载...

$users->take(20)->all();

// 前 5 个用户来自集合的缓存... 其余的从数据库中加载...