Skip to content

集合

简介

Illuminate\Support\Collection 类为处理数据数组提供了一个流畅且便捷的封装层。来看下面这段代码。我们会使用 collect 辅助函数从数组创建一个新的集合实例,对每个元素运行 strtoupper 函数,然后移除所有空元素:

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

如你所见,Collection 类允许你链式调用其方法,对底层数组执行流畅的映射和归并操作。一般来说,集合是不可变的,这意味着每个 Collection 方法都会返回一个全新的 Collection 实例。

创建集合

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

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

你也可以使用 makefromJson 方法来创建集合。

NOTE

Eloquent 查询的结果始终会以 Collection 实例的形式返回。

扩展集合

集合是 "macroable" 的,这使你可以在运行时向 Collection 类添加额外的方法。Illuminate\Support\Collection 类的 macro 方法接收一个闭包,当你的宏被调用时就会执行它。这个宏闭包可以通过 $this 访问集合的其他方法,就像它本来就是集合类的真实方法一样。例如,下面的代码向 Collection 类添加了一个 toUpper 方法:

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

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

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

$upper = $collection->toUpper();

// ['FIRST', 'SECOND']

通常,你应该在 service providerboot 方法中声明集合宏。

宏参数

如果有需要,你可以定义接受额外参数的宏:

php
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;

Collection::macro('toLocale', function (string $locale) {
    return $this->map(function (string $value) use ($locale) {
        return Lang::get($value, [], $locale);
    });
});

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

$translated = $collection->toLocale('es');

// ['primero', 'segundo'];

可用方法

在接下来的大部分集合文档中,我们会讨论 Collection 类上可用的每个方法。请记住,所有这些方法都可以进行链式调用,以流畅地操作底层数组。此外,几乎每个方法都会返回一个新的 Collection 实例,从而让你在需要时保留集合的原始副本:

方法列表

after() {.collection-method .first-collection-method}

after 方法返回给定项目之后的那个项目。如果找不到给定项目,或者它已经是最后一个项目,则会返回 null

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

$collection->after(3);

// 4

$collection->after(5);

// null

该方法使用“宽松”比较来搜索给定项目,这意味着包含整数值的字符串会被视为与相同值的整数相等。若要使用“严格”比较,你可以向该方法传入 strict 参数:

php
collect([2, 4, 6, 8])->after('4', strict: true);

// null

另外,你也可以提供自己的闭包,以搜索第一个通过给定条件测试的项目:

php
collect([2, 4, 6, 8])->after(function (int $item, int $key) {
    return $item > 5;
});

// 8

all() {.collection-method}

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

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

// [1, 2, 3]

average() {.collection-method}

avg 方法的别名。

avg() {.collection-method}

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

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

// 20

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

// 2

before() {.collection-method}

before 方法与 after 方法相反。它返回给定项目之前的那个项目。如果找不到给定项目,或者它已经是第一个项目,则会返回 null

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

$collection->before(3);

// 2

$collection->before(1);

// null

collect([2, 4, 6, 8])->before('4', strict: true);

// null

collect([2, 4, 6, 8])->before(function (int $item, int $key) {
    return $item > 5;
});

// 4

chunk() {.collection-method}

chunk 方法会将集合拆分为多个给定大小的较小集合:

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

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

$chunks->all();

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

views 中配合 Bootstrap 这类网格系统工作时,这个方法尤其有用。例如,假设你有一组想以网格形式展示的 Eloquent model:

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

chunkWhile() {.collection-method}

chunkWhile 方法会根据给定回调的求值结果,将集合拆分为多个较小的集合。传递给闭包的 $chunk 变量可用于检查前一个元素:

php
$collection = collect(str_split('AABBCCCD'));

$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) {
    return $value === $chunk->last();
});

$chunks->all();

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

collapse() {.collection-method}

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]

collapseWithKeys() {.collection-method}

collapseWithKeys 方法会将由数组或集合组成的集合压平成一个集合,同时保留原始键名。如果该集合本身已经是单层的,则会返回一个空集合:

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

$collapsed = $collection->collapseWithKeys();

$collapsed->all();

// [
//     'first'  => [1, 2, 3],
//     'second' => [4, 5, 6],
//     'third'  => [7, 8, 9],
// ]

collect() {.collection-method}

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();

$collection::class;

// 'Illuminate\Support\Collection'

$collection->all();

// [1, 2, 3]

NOTE

当你拥有一个 Enumerable 实例并且需要一个非惰性的集合实例时,collect 方法尤其有用。由于 collect()Enumerable contract 的一部分,你可以放心使用它来获取一个 Collection 实例。

combine() {.collection-method}

combine 方法会把当前集合的值作为键,与另一个数组或集合的值组合起来:

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

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

$combined->all();

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

concat() {.collection-method}

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

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

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

$concatenated->all();

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

concat 方法会对追加到原始集合上的项目按数字重新索引键名。如果你想在关联集合中保留键名,请参阅 merge 方法。

contains() {.collection-method}

contains 方法用于判断集合中是否包含给定项目。你可以向 contains 方法传入一个闭包,以判断集合中是否存在满足给定条件测试的元素:

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

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

// false

或者,你也可以向 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 方法在检查项目值时使用“宽松”比较,这意味着带有整数值的字符串会被视为与相同值的整数相等。若要使用“严格”比较,请改用 containsStrict 方法。

若要获取 contains 的反向行为,请参阅 doesntContain 方法。

containsStrict() {.collection-method}

该方法与 contains 方法具有相同的签名;不过,所有值都会使用“严格”比较。

NOTE

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

count() {.collection-method}

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

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

$collection->count();

// 4

countBy() {.collection-method}

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 (string $email) {
    return substr(strrchr($email, '@'), 1);
});

$counted->all();

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

crossJoin() {.collection-method}

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() {.collection-method}

dd 方法会转储集合中的项目并终止脚本执行:

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

$collection->dd();

/*
    array:2 [
        0 => "John Doe"
        1 => "Jane Doe"
    ]
*/

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

diff() {.collection-method}

diff 方法会基于值将集合与另一个集合或普通 PHP array 进行比较。该方法会返回原始集合中那些不存在于给定集合中的值:

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

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

$diff->all();

// [1, 3, 5]

NOTE

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

diffAssoc() {.collection-method}

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]

diffAssocUsing() {.collection-method}

diffAssoc 不同,diffAssocUsing 接受一个用户提供的回调函数来比较索引:

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

$diff = $collection->diffAssocUsing([
    'Color' => 'yellow',
    'Type' => 'fruit',
    'Remain' => 3,
], 'strnatcasecmp');

$diff->all();

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

该回调必须是一个比较函数,返回值需要是小于、等于或大于零的整数。更多信息请参阅 PHP 关于 array_diff_uassoc 的文档,diffAssocUsing 方法在内部正是使用了这个 PHP 函数。

diffKeys() {.collection-method}

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]

doesntContain() {.collection-method}

doesntContain 方法用于判断集合中是否不包含给定项目。你可以向 doesntContain 方法传入一个闭包,以判断集合中是否不存在满足给定条件测试的元素:

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

$collection->doesntContain(function (int $value, int $key) {
    return $value < 5;
});

// false

或者,你也可以向 doesntContain 方法传入一个字符串,以判断集合中是否不包含给定项目值:

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

$collection->doesntContain('Table');

// true

$collection->doesntContain('Desk');

// false

你还可以向 doesntContain 方法传入一个键 / 值对,以判断集合中是否不存在给定的键值对:

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

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

// true

doesntContain 方法在检查项目值时使用“宽松”比较,这意味着带有整数值的字符串会被视为与相同值的整数相等。

doesntContainStrict() {.collection-method}

该方法与 doesntContain 方法具有相同的签名;不过,所有值都会使用“严格”比较。

dot() {.collection-method}

dot 方法会将多维集合压平成一个单层集合,并使用“点”表示法来表示嵌套深度:

php
$collection = collect(['products' => ['desk' => ['price' => 100]]]);

$flattened = $collection->dot();

$flattened->all();

// ['products.desk.price' => 100]

dump() {.collection-method}

dump 方法会转储集合中的项目:

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

$collection->dump();

/*
    array:2 [
        0 => "John Doe"
        1 => "Jane Doe"
    ]
*/

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

duplicates() {.collection-method}

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() {.collection-method}

该方法与 duplicates 方法具有相同的签名;不过,所有值都会使用“严格”比较。

each() {.collection-method}

each 方法会遍历集合中的项目,并将每个项目传递给一个闭包:

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

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

如果你想停止遍历这些项目,可以在闭包中返回 false

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

eachSpread() {.collection-method}

eachSpread 方法会遍历集合中的项目,并将每个嵌套项目的值展开后传给给定回调:

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

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

你可以通过让回调返回 false 来停止遍历这些项目:

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

ensure() {.collection-method}

ensure 方法可用于验证集合中的所有元素是否都属于给定类型或某个类型列表。否则会抛出 UnexpectedValueException

php
return $collection->ensure(User::class);

return $collection->ensure([User::class, Customer::class]);

你也可以指定 stringintfloatboolarray 这类基础类型:

php
return $collection->ensure('int');

WARNING

ensure 方法并不能保证后续不会向集合中再添加其他类型的元素。

every() {.collection-method}

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

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

// false

如果集合为空,every 方法会返回 true:

php
$collection = collect([]);

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

// true

except() {.collection-method}

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

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

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

$filtered->all();

// ['product_id' => 1]

若要获取 except 的反向行为,请参阅 only 方法。

NOTE

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

filter() {.collection-method}

filter 方法会使用给定回调过滤集合,只保留通过给定条件测试的项目:

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

$filtered = $collection->filter(function (int $value, int $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() {.collection-method}

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

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

// 3

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

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

// 1

firstOrFail() {.collection-method}

firstOrFail 方法与 first 方法完全相同;不过,如果没有找到结果,则会抛出 Illuminate\Support\ItemNotFoundException 异常:

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

// Throws ItemNotFoundException...

你也可以在不传参数的情况下调用 firstOrFail 方法,以获取集合中的第一个元素。如果集合为空,则会抛出 Illuminate\Support\ItemNotFoundException 异常:

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

// Throws ItemNotFoundException...

firstWhere() {.collection-method}

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 方法会返回第一个给定项目键值为“truthy”的项目:

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

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

flatMap() {.collection-method}

flatMap 方法会遍历集合,并将每个值传给给定闭包。闭包可以自由修改项目并将其返回,从而形成一个包含修改后项目的新集合。随后,数组会被压平一层:

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

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

$flattened->all();

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

flatten() {.collection-method}

flatten 方法会将多维集合压平成一维集合:

php
$collection = collect([
    'name' => 'Taylor',
    'languages' => [
        'PHP', 'JavaScript'
    ]
]);

$flattened = $collection->flatten();

$flattened->all();

// ['Taylor', 'PHP', 'JavaScript'];

如果有需要,你可以向 flatten 方法传入一个“深度”参数:

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() {.collection-method}

flip 方法会交换集合中的键和值:

php
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);

$flipped = $collection->flip();

$flipped->all();

// ['Taylor' => 'name', 'Laravel' => 'framework']

forget() {.collection-method}

forget 方法会根据键从集合中移除某个项目:

php
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);

// Forget a single key...
$collection->forget('name');

// ['framework' => 'Laravel']

// Forget multiple keys...
$collection->forget(['name', 'framework']);

// []

WARNING

与大多数其他集合方法不同,forget 不会返回一个新的已修改集合;它会直接修改并返回它所调用的那个集合。

forPage() {.collection-method}

forPage 方法会返回一个新集合,其中包含指定页码上应出现的项目。该方法的第一个参数是页码,第二个参数是每页显示的项目数:

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

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

$chunk->all();

// [4, 5, 6]

fromJson() {.collection-method}

静态 fromJson 方法会使用 PHP 的 json_decode 函数解码给定 JSON 字符串,从而创建一个新的集合实例:

php
use Illuminate\Support\Collection;

$json = json_encode([
    'name' => 'Taylor Otwell',
    'role' => 'Developer',
    'status' => 'Active',
]);

$collection = Collection::fromJson($json);

get() {.collection-method}

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

php
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);

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

// Taylor

你也可以选择传入一个默认值作为第二个参数:

php
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);

$value = $collection->get('age', 34);

// 34

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

php
$collection->get('email', function () {
    return 'taylor@example.com';
});

// taylor@example.com

groupBy() {.collection-method}

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->all();

/*
    [
        '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 (array $item, int $key) {
    return substr($item['account_id'], -3);
});

$grouped->all();

/*
    [
        '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 (array $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() {.collection-method}

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

hasAny() {.collection-method}

hasAny 方法用于判断给定键中是否有任意一个存在于集合中:

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

$collection->hasAny(['product', 'price']);

// true

$collection->hasAny(['name', 'price']);

// false

hasMany() {.collection-method}

hasMany 方法用于判断集合是否包含多个项目:

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

// false

collect(['1'])->hasMany();

// false

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

// true

collect([
    ['age' => 2],
    ['age' => 3],
])->hasMany(fn ($item) => $item['age'] === 2)

// false

hasSole() {.collection-method}

hasSole 方法用于判断集合中是否只包含一个项目,也可以选择附带给定条件进行匹配:

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

// false

collect(['1'])->hasSole();

// true

collect([1, 2, 3])->hasSole(fn (int $item) => $item === 2);

// true

implode() {.collection-method}

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'

如果你想先格式化将要被拼接的值,也可以向 implode 方法传入一个闭包:

php
$collection->implode(function (array $item, int $key) {
    return strtoupper($item['product']);
}, ', ');

// 'DESK, CHAIR'

intersect() {.collection-method}

intersect 方法会从原始集合中移除所有不存在于给定数组或集合中的值。返回结果会保留原始集合的键名:

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

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

$intersect->all();

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

NOTE

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

intersectUsing() {.collection-method}

intersectUsing 方法会从原始集合中移除所有不存在于给定数组或集合中的值,并使用自定义回调来比较这些值。返回结果会保留原始集合的键名:

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

$intersect = $collection->intersectUsing(['desk', 'chair', 'bookcase'], function (string $a, string $b) {
    return strcasecmp($a, $b);
});

$intersect->all();

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

intersectAssoc() {.collection-method}

intersectAssoc 方法会将原始集合与另一个集合或数组进行比较,并返回所有给定集合中都存在的键 / 值对:

php
$collection = collect([
    'color' => 'red',
    'size' => 'M',
    'material' => 'cotton'
]);

$intersect = $collection->intersectAssoc([
    'color' => 'blue',
    'size' => 'M',
    'material' => 'polyester'
]);

$intersect->all();

// ['size' => 'M']

intersectAssocUsing() {.collection-method}

intersectAssocUsing 方法会将原始集合与另一个集合或数组进行比较,并返回两者中都存在的键 / 值对,同时使用自定义比较回调来判断键和值是否相等:

php
$collection = collect([
    'color' => 'red',
    'Size' => 'M',
    'material' => 'cotton',
]);

$intersect = $collection->intersectAssocUsing([
    'color' => 'blue',
    'size' => 'M',
    'material' => 'polyester',
], function (string $a, string $b) {
    return strcasecmp($a, $b);
});

$intersect->all();

// ['Size' => 'M']

intersectByKeys() {.collection-method}

intersectByKeys 方法会从原始集合中移除所有不存在于给定数组或集合中的键及其对应值:

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() {.collection-method}

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

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

// true

isNotEmpty() {.collection-method}

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

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

// false

join() {.collection-method}

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() {.collection-method}

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 (array $item, int $key) {
    return strtoupper($item['product_id']);
});

$keyed->all();

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

keys() {.collection-method}

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() {.collection-method}

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

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

// 2

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

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

// 4

lazy() {.collection-method}

lazy 方法会基于底层数组中的项目返回一个新的 LazyCollection 实例:

php
$lazyCollection = collect([1, 2, 3, 4])->lazy();

$lazyCollection::class;

// Illuminate\Support\LazyCollection

$lazyCollection->all();

// [1, 2, 3, 4]

当你需要对一个包含大量项目的巨大 Collection 执行转换操作时,这一点尤其有用:

php
$count = $hugeCollection
    ->lazy()
    ->where('country', 'FR')
    ->where('balance', '>', '100')
    ->count();

通过将集合转换为 LazyCollection,我们可以避免分配大量额外内存。虽然原始集合仍会将它自己的值保留在内存中,但后续的过滤操作不会再这样做。因此,在过滤集合结果时几乎不会分配额外内存。

macro() {.collection-method}

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

make() {.collection-method}

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

php
use Illuminate\Support\Collection;

$collection = Collection::make([1, 2, 3]);

map() {.collection-method}

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

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

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

$multiplied->all();

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

WARNING

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

mapInto() {.collection-method}

mapInto() 方法会遍历集合,并将值传入构造函数,以创建给定类的新实例:

php
class Currency
{
    /**
     * Create a new currency instance.
     */
    function __construct(
        public string $code,
    ) {}
}

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

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

$currencies->all();

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

mapSpread() {.collection-method}

mapSpread 方法会遍历集合中的项目,并将每个嵌套项目的值展开后传给给定闭包。闭包可以自由修改项目并将其返回,从而形成一个由修改后项目组成的新集合:

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

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

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

$sequence->all();

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

mapToGroups() {.collection-method}

mapToGroups 方法会按照给定闭包对集合中的项目进行分组。该闭包应返回一个只包含单个键 / 值对的关联数组,从而形成一个新的分组值集合:

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

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

$grouped->all();

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

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

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

mapWithKeys() {.collection-method}

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

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

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

$keyed->all();

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

max() {.collection-method}

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

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

// 20

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

// 5

median() {.collection-method}

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() {.collection-method}

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() {.collection-method}

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() {.collection-method}

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

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

// 10

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

// 1

mode() {.collection-method}

mode 方法返回给定键的众数

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

// [10]

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

// [1]

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

// [1, 2]

multiply() {.collection-method}

multiply 方法会为集合中的所有项目创建指定数量的副本:

php
$users = collect([
    ['name' => 'User #1', 'email' => 'user1@example.com'],
    ['name' => 'User #2', 'email' => 'user2@example.com'],
])->multiply(3);

/*
    [
        ['name' => 'User #1', 'email' => 'user1@example.com'],
        ['name' => 'User #2', 'email' => 'user2@example.com'],
        ['name' => 'User #1', 'email' => 'user1@example.com'],
        ['name' => 'User #2', 'email' => 'user2@example.com'],
        ['name' => 'User #1', 'email' => 'user1@example.com'],
        ['name' => 'User #2', 'email' => 'user2@example.com'],
    ]
*/

nth() {.collection-method}

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

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

$collection->nth(4);

// ['a', 'e']

你也可以选择传入起始偏移量作为第二个参数:

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

// ['b', 'f']

only() {.collection-method}

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 方法。

NOTE

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

pad() {.collection-method}

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

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

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() {.collection-method}

partition 方法可以与 PHP 的数组解构配合使用,用于将通过给定条件测试的元素与未通过的元素分开:

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

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

$underThree->all();

// [1, 2]

$equalOrAboveThree->all();

// [3, 4, 5, 6]

NOTE

Eloquent collections 交互时,该方法的行为会有所不同。

percentage() {.collection-method}

percentage 方法可用于快速计算集合中通过给定条件测试的项目所占百分比:

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

$percentage = $collection->percentage(fn (int $value) => $value === 1);

// 33.33

默认情况下,百分比会四舍五入到两位小数。不过,你可以通过向该方法提供第二个参数来自定义这一行为:

php
$percentage = $collection->percentage(fn (int $value) => $value === 1, precision: 3);

// 33.333

pipe() {.collection-method}

pipe 方法会将集合传给给定闭包,并返回该闭包执行后的结果:

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

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

// 6

pipeInto() {.collection-method}

pipeInto 方法会创建给定类的新实例,并将集合传入其构造函数:

php
class ResourceCollection
{
    /**
     * Create a new ResourceCollection instance.
     */
    public function __construct(
        public Collection $collection,
    ) {}
}

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

$resource = $collection->pipeInto(ResourceCollection::class);

$resource->collection->all();

// [1, 2, 3]

pipeThrough() {.collection-method}

pipeThrough 方法会将集合依次传给给定闭包数组中的各个闭包,并返回这些闭包执行后的结果:

php
use Illuminate\Support\Collection;

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

$result = $collection->pipeThrough([
    function (Collection $collection) {
        return $collection->merge([4, 5]);
    },
    function (Collection $collection) {
        return $collection->sum();
    },
]);

// 15

pluck() {.collection-method}

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']

pluck 方法还支持使用“点”表示法获取嵌套值:

php
$collection = collect([
    [
        'name' => 'Laracon',
        'speakers' => [
            'first_day' => ['Rosa', 'Judith'],
        ],
    ],
    [
        'name' => 'VueConf',
        'speakers' => [
            'first_day' => ['Abigail', 'Joey'],
        ],
    ],
]);

$plucked = $collection->pluck('speakers.first_day');

$plucked->all();

// [['Rosa', 'Judith'], ['Abigail', 'Joey']]

如果存在重复键,则最后一个匹配的元素会被放入取出的集合中:

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() {.collection-method}

pop 方法会移除并返回集合中的最后一个项目。如果集合为空,则返回 null

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

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]

你可以向 pop 方法传入一个整数,以从集合末尾移除并返回多个项目:

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

$collection->pop(3);

// collect([5, 4, 3])

$collection->all();

// [1, 2]

prepend() {.collection-method}

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() {.collection-method}

pull 方法会根据键从集合中移除并返回一个项目:

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

$collection->pull('name');

// 'Desk'

$collection->all();

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

push() {.collection-method}

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

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

$collection->push(5);

$collection->all();

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

你也可以提供多个项目,一并追加到集合末尾:

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

$collection->push(5, 6, 7);
 
$collection->all();
 
// [1, 2, 3, 4, 5, 6, 7]

put() {.collection-method}

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

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

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

$collection->all();

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

random() {.collection-method}

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

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

$collection->random();

// 4 - (retrieved randomly)

你可以向 random 传入一个整数,以指定想随机获取多少个项目。当你显式传入希望获取的项目数时,返回值始终是一个集合:

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

$random->all();

// [2, 4, 5] - (retrieved randomly)

如果集合实例中的项目数少于请求的数量,random 方法会抛出 InvalidArgumentException

random 方法也接受一个闭包,该闭包会接收当前集合实例:

php
use Illuminate\Support\Collection;

$random = $collection->random(fn (Collection $items) => min(10, count($items)));

$random->all();

// [1, 2, 3, 4, 5] - (retrieved randomly)

range() {.collection-method}

range 方法会返回一个集合,其中包含指定范围内的整数:

php
$collection = collect()->range(3, 6);

$collection->all();

// [3, 4, 5, 6]

reduce() {.collection-method}

reduce 方法会将集合归并为单个值,并将每次迭代的结果传入下一次迭代:

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

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

// 6

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

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

// 10

reduce 方法还会将数组键传给给定回调:

php
$collection = collect([
    'usd' => 1400,
    'gbp' => 1200,
    'eur' => 1000,
]);

$ratio = [
    'usd' => 1,
    'gbp' => 1.37,
    'eur' => 1.22,
];

$collection->reduce(function (int $carry, int $value, string $key) use ($ratio) {
    return $carry + ($value * $ratio[$key]);
}, 0);

// 4264

reduceSpread() {.collection-method}

reduceSpread 方法会将集合归并为一个值数组,并将每次迭代的结果传入下一次迭代。该方法与 reduce 类似;不过,它可以接受多个初始值:

php
[$creditsRemaining, $batch] = Image::where('status', 'unprocessed')
    ->get()
    ->reduceSpread(function (int $creditsRemaining, Collection $batch, Image $image) {
        if ($creditsRemaining >= $image->creditsRequired()) {
            $batch->push($image);

            $creditsRemaining -= $image->creditsRequired();
        }

        return [$creditsRemaining, $batch];
    }, $creditsAvailable, collect());

reject() {.collection-method}

reject 方法会使用给定闭包过滤集合。如果某个项目应从结果集合中移除,则闭包应返回 true

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

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

$filtered->all();

// [1, 2]

若要获取 reject 的反向行为,请参阅 filter 方法。

replace() {.collection-method}

replace 方法的行为与 merge 类似;不过,除了会覆盖具有相同字符串键的项目外,replace 还会覆盖集合中具有相同数字键的项目:

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

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

$replaced->all();

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

replaceRecursive() {.collection-method}

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() {.collection-method}

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
collect([2, 4, 6, 8])->search('4', strict: true);

// false

另外,你也可以提供自己的闭包,以搜索第一个通过给定条件测试的项目:

php
collect([2, 4, 6, 8])->search(function (int $item, int $key) {
    return $item > 5;
});

// 2

select() {.collection-method}

select 方法会从集合中选择给定键,类似于 SQL SELECT 语句:

php
$users = collect([
    ['name' => 'Taylor Otwell', 'role' => 'Developer', 'status' => 'active'],
    ['name' => 'Victoria Faith', 'role' => 'Researcher', 'status' => 'active'],
]);

$users->select(['name', 'role']);

/*
    [
        ['name' => 'Taylor Otwell', 'role' => 'Developer'],
        ['name' => 'Victoria Faith', 'role' => 'Researcher'],
    ],
*/

shift() {.collection-method}

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

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

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]

你可以向 shift 方法传入一个整数,以从集合开头移除并返回多个项目:

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

$collection->shift(3);

// collect([1, 2, 3])

$collection->all();

// [4, 5]

shuffle() {.collection-method}

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

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

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (generated randomly)

skip() {.collection-method}

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]

skipUntil() {.collection-method}

skipUntil 方法会在给定回调返回 false 时持续跳过集合中的项目。一旦回调返回 true,集合中剩余的所有项目都会作为一个新集合返回:

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

$subset = $collection->skipUntil(function (int $item) {
    return $item >= 3;
});

$subset->all();

// [3, 4]

你也可以向 skipUntil 方法传入一个简单值,以跳过所有项目,直到找到给定值为止:

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

$subset = $collection->skipUntil(3);

$subset->all();

// [3, 4]

WARNING

如果未找到给定值,或者回调始终不返回 true,则 skipUntil 方法会返回一个空集合。

skipWhile() {.collection-method}

skipWhile 方法会在给定回调返回 true 时持续跳过集合中的项目。一旦回调返回 false,集合中剩余的所有项目都会作为一个新集合返回:

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

$subset = $collection->skipWhile(function (int $item) {
    return $item <= 3;
});

$subset->all();

// [4]

WARNING

如果回调始终不返回 false,则 skipWhile 方法会返回一个空集合。

slice() {.collection-method}

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 方法重新索引。

sliding() {.collection-method}

sliding 方法会返回一个新的块集合,用于表示集合项目的“滑动窗口”视图:

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

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

$chunks->toArray();

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

它与 eachSpread 方法配合使用时尤其有用:

php
$transactions->sliding(2)->eachSpread(function (Collection $previous, Collection $current) {
    $current->total = $previous->total + $current->amount;
});

你也可以选择传入第二个“步长”值,用来决定每个块首项之间的间距:

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

$chunks = $collection->sliding(3, step: 2);

$chunks->toArray();

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

sole() {.collection-method}

sole 方法会返回集合中第一个通过给定条件测试的元素,但前提是该条件恰好只匹配一个元素:

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

// 2

你也可以向 sole 方法传入一个键 / 值对,它会返回集合中第一个匹配该键值对的元素,但前提是恰好只有一个元素匹配:

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

$collection->sole('product', 'Chair');

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

另外,如果集合中只有一个元素,你也可以在不传参数的情况下调用 sole 方法以获取该元素:

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

$collection->sole();

// ['product' => 'Desk', 'price' => 200]

如果集合中没有任何元素应由 sole 方法返回,则会抛出 \Illuminate\Collections\ItemNotFoundException 异常。如果应返回的元素多于一个,则会抛出 \Illuminate\Collections\MultipleItemsFoundException

some() {.collection-method}

contains 方法的别名。

sort() {.collection-method}

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 方法在内部正是调用了它。

NOTE

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

sortBy() {.collection-method}

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],
    ]
*/

sortBy 方法接受 sort flags 作为第二个参数:

php
$collection = collect([
    ['title' => 'Item 1'],
    ['title' => 'Item 12'],
    ['title' => 'Item 3'],
]);

$sorted = $collection->sortBy('title', SORT_NATURAL);

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

/*
    [
        ['title' => 'Item 1'],
        ['title' => 'Item 3'],
        ['title' => 'Item 12'],
    ]
*/

另外,你也可以传入自己的闭包来决定如何对集合中的值排序:

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

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

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

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

如果你想按多个属性对集合排序,可以向 sortBy 方法传入一个排序操作数组。每个排序操作都应是一个数组,包含你希望排序的属性以及期望的排序方向:

php
$collection = collect([
    ['name' => 'Taylor Otwell', 'age' => 34],
    ['name' => 'Abigail Otwell', 'age' => 30],
    ['name' => 'Taylor Otwell', 'age' => 36],
    ['name' => 'Abigail Otwell', 'age' => 32],
]);

$sorted = $collection->sortBy([
    ['name', 'asc'],
    ['age', 'desc'],
]);

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

/*
    [
        ['name' => 'Abigail Otwell', 'age' => 32],
        ['name' => 'Abigail Otwell', 'age' => 30],
        ['name' => 'Taylor Otwell', 'age' => 36],
        ['name' => 'Taylor Otwell', 'age' => 34],
    ]
*/

按多个属性对集合排序时,你也可以提供闭包来定义每一个排序操作:

php
$collection = collect([
    ['name' => 'Taylor Otwell', 'age' => 34],
    ['name' => 'Abigail Otwell', 'age' => 30],
    ['name' => 'Taylor Otwell', 'age' => 36],
    ['name' => 'Abigail Otwell', 'age' => 32],
]);

$sorted = $collection->sortBy([
    fn (array $a, array $b) => $a['name'] <=> $b['name'],
    fn (array $a, array $b) => $b['age'] <=> $a['age'],
]);

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

/*
    [
        ['name' => 'Abigail Otwell', 'age' => 32],
        ['name' => 'Abigail Otwell', 'age' => 30],
        ['name' => 'Taylor Otwell', 'age' => 36],
        ['name' => 'Taylor Otwell', 'age' => 34],
    ]
*/

sortByDesc() {.collection-method}

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

sortDesc() {.collection-method}

该方法会按与 sort 方法相反的顺序对集合进行排序:

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

$sorted = $collection->sortDesc();

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

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

sort 不同,你不能向 sortDesc 传入闭包。你应改用 sort 方法,并反转你的比较逻辑。

sortKeys() {.collection-method}

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

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

$sorted = $collection->sortKeys();

$sorted->all();

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

sortKeysDesc() {.collection-method}

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

sortKeysUsing() {.collection-method}

sortKeysUsing 方法会使用回调按照底层关联数组的键名对集合进行排序:

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

$sorted = $collection->sortKeysUsing('strnatcasecmp');

$sorted->all();

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

该回调必须是一个比较函数,返回值需要是小于、等于或大于零的整数。更多信息请参阅 PHP 关于 uksort 的文档,sortKeysUsing 方法在内部正是使用了这个 PHP 函数。

splice() {.collection-method}

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() {.collection-method}

split 方法会将集合拆分为给定数量的组:

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

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

$groups->all();

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

splitIn() {.collection-method}

splitIn 方法会将集合拆分为给定数量的组,并先尽量填满非末尾组,再将余数分配给最后一组:

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

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

$groups->all();

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

sum() {.collection-method}

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 (array $product) {
    return count($product['colors']);
});

// 6

take() {.collection-method}

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]

takeUntil() {.collection-method}

takeUntil 方法会返回集合中的项目,直到给定回调返回 true 为止:

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

$subset = $collection->takeUntil(function (int $item) {
    return $item >= 3;
});

$subset->all();

// [1, 2]

你也可以向 takeUntil 方法传入一个简单值,以获取项目直到找到给定值为止:

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

$subset = $collection->takeUntil(3);

$subset->all();

// [1, 2]

WARNING

如果未找到给定值,或者回调始终不返回 true,则 takeUntil 方法会返回集合中的所有项目。

takeWhile() {.collection-method}

takeWhile 方法会返回集合中的项目,直到给定回调返回 false 为止:

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

$subset = $collection->takeWhile(function (int $item) {
    return $item < 3;
});

$subset->all();

// [1, 2]

WARNING

如果回调始终不返回 false,则 takeWhile 方法会返回集合中的所有项目。

tap() {.collection-method}

tap 方法会将集合传给给定回调,使你能够在特定节点“插入”到集合处理流程中,对项目执行某些操作而不影响集合本身。之后,tap 方法会返回该集合:

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

// 1

times() {.collection-method}

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

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

$collection->all();

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

toArray() {.collection-method}

toArray 方法会将集合转换为普通 PHP array。如果集合中的值是 Eloquent model,这些 model 也会被转换为数组:

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

$collection->toArray();

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

WARNING

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

toJson() {.collection-method}

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

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

$collection->toJson();

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

toPrettyJson() {.collection-method}

toPrettyJson 方法会使用 JSON_PRETTY_PRINT 选项将集合转换为格式化后的 JSON 字符串:

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

$collection->toPrettyJson();

transform() {.collection-method}

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

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

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

$collection->all();

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

WARNING

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

undot() {.collection-method}

undot 方法会将使用“点”表示法的一维集合展开为多维集合:

php
$person = collect([
    'name.first_name' => 'Marie',
    'name.last_name' => 'Valentine',
    'address.line_1' => '2992 Eagle Drive',
    'address.line_2' => '',
    'address.suburb' => 'Detroit',
    'address.state' => 'MI',
    'address.postcode' => '48219'
]);

$person = $person->undot();

$person->toArray();

/*
    [
        "name" => [
            "first_name" => "Marie",
            "last_name" => "Valentine",
        ],
        "address" => [
            "line_1" => "2992 Eagle Drive",
            "line_2" => "",
            "suburb" => "Detroit",
            "state" => "MI",
            "postcode" => "48219",
        ],
    ]
*/

union() {.collection-method}

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

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

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

$union->all();

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

unique() {.collection-method}

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'],
    ]
*/

最后,你也可以向 unique 方法传入自己的闭包,以指定应由哪个值来决定项目的唯一性:

php
$unique = $collection->unique(function (array $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 方法。

NOTE

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

uniqueStrict() {.collection-method}

该方法与 unique 方法具有相同的签名;不过,所有值都会使用“严格”比较。

unless() {.collection-method}

unless 方法会在传给该方法的第一个参数求值结果不为 true 时执行给定回调。集合实例以及传给 unless 方法的第一个参数都会提供给闭包:

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

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

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

$collection->all();

// [1, 2, 3, 5]

你还可以向 unless 方法传入第二个回调。当传给 unless 方法的第一个参数求值结果为 true 时,会执行第二个回调:

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

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

$collection->all();

// [1, 2, 3, 5]

若要获取 unless 的反向行为,请参阅 when 方法。

unlessEmpty() {.collection-method}

whenNotEmpty 方法的别名。

unlessNotEmpty() {.collection-method}

whenEmpty 方法的别名。

unwrap() {.collection-method}

静态 unwrap 方法会在适用时从给定值中返回集合的底层项目:

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

// ['John Doe']

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

// ['John Doe']

Collection::unwrap('John Doe');

// 'John Doe'

value() {.collection-method}

value 方法会从集合的第一个元素中取出给定值:

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

$value = $collection->value('price');

// 200

values() {.collection-method}

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

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

$values = $collection->values();

$values->all();

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

when() {.collection-method}

when 方法会在传给该方法的第一个参数求值结果为 true 时执行给定回调。集合实例以及传给 when 方法的第一个参数都会提供给闭包:

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

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

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

$collection->all();

// [1, 2, 3, 4]

你还可以向 when 方法传入第二个回调。当传给 when 方法的第一个参数求值结果为 false 时,会执行第二个回调:

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

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

$collection->all();

// [1, 2, 3, 5]

若要获取 when 的反向行为,请参阅 unless 方法。

whenEmpty() {.collection-method}

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

php
$collection = collect(['Michael', 'Tom']);

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

$collection->all();

// ['Michael', 'Tom']

$collection = collect();

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

$collection->all();

// ['Adam']

你还可以向 whenEmpty 方法传入第二个闭包,它会在集合不为空时执行:

php
$collection = collect(['Michael', 'Tom']);

$collection->whenEmpty(function (Collection $collection) {
    return $collection->push('Adam');
}, function (Collection $collection) {
    return $collection->push('Taylor');
});

$collection->all();

// ['Michael', 'Tom', 'Taylor']

若要获取 whenEmpty 的反向行为,请参阅 whenNotEmpty 方法。

whenNotEmpty() {.collection-method}

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

php
$collection = collect(['Michael', 'Tom']);

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

$collection->all();

// ['Michael', 'Tom', 'Adam']

$collection = collect();

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

$collection->all();

// []

你还可以向 whenNotEmpty 方法传入第二个闭包,它会在集合为空时执行:

php
$collection = collect();

$collection->whenNotEmpty(function (Collection $collection) {
    return $collection->push('Adam');
}, function (Collection $collection) {
    return $collection->push('Taylor');
});

$collection->all();

// ['Taylor']

若要获取 whenNotEmpty 的反向行为,请参阅 whenEmpty 方法。

where() {.collection-method}

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 方法;若要针对 null 值过滤,请使用 whereNullwhereNotNull 方法。

你也可以选择将比较运算符作为第二个参数传入。支持的运算符包括:===!==!====<>><>=<=

php
$collection = collect([
    ['name' => 'Jim', 'platform' => 'Mac'],
    ['name' => 'Sally', 'platform' => 'Mac'],
    ['name' => 'Sue', 'platform' => 'Linux'],
]);

$filtered = $collection->where('platform', '!=', 'Linux');

$filtered->all();

/*
    [
        ['name' => 'Jim', 'platform' => 'Mac'],
        ['name' => 'Sally', 'platform' => 'Mac'],
    ]
*/

whereStrict() {.collection-method}

该方法与 where 方法具有相同的签名;不过,所有值都会使用“严格”比较。

whereBetween() {.collection-method}

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() {.collection-method}

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() {.collection-method}

该方法与 whereIn 方法具有相同的签名;不过,所有值都会使用“严格”比较。

whereInstanceOf() {.collection-method}

whereInstanceOf 方法会按给定类类型过滤集合:

php
use App\Models\User;
use App\Models\Post;

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

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

$filtered->all();

// [App\Models\User, App\Models\User]

whereNotBetween() {.collection-method}

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() {.collection-method}

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() {.collection-method}

该方法与 whereNotIn 方法具有相同的签名;不过,所有值都会使用“严格”比较。

whereNotNull() {.collection-method}

whereNotNull 方法会返回集合中给定键不为 null 的项目:

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

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

$filtered->all();

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

whereNull() {.collection-method}

whereNull 方法会返回集合中给定键为 null 的项目:

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

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

$filtered->all();

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

wrap() {.collection-method}

静态 wrap 方法会在适用时将给定值包裹为一个集合:

php
use Illuminate\Support\Collection;

$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() {.collection-method}

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

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

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

$zipped->all();

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

高阶消息

集合还支持“高阶消息”,它是对集合执行常见操作的快捷方式。提供高阶消息的集合方法包括:averageavgcontainseacheveryfilterfirstflatMapgroupBykeyBymapmaxminpartitionrejectskipUntilskipWhilesomesortBysortByDescsumtakeUntiltakeWhile 以及 unique

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

php
use App\Models\User;

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

$users->each->markAsVip();

同样地,我们可以使用 sum 高阶消息来汇总一组用户的 votes 总数:

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

return $users->sum->votes;

惰性集合

简介

WARNING

在进一步了解 Laravel 的惰性集合之前,请先花一些时间熟悉 PHP generators

为了补充已经很强大的 Collection 类,LazyCollection 类利用 PHP 的 generators,让你在保持较低内存占用的同时处理非常大的数据集。

例如,假设你的应用程序需要处理一个数 GB 的日志文件,同时还要利用 Laravel 的集合方法来解析这些日志。你不必一次性把整个文件读入内存,而是可以使用惰性集合,在任意时刻只将文件的一小部分保留在内存中:

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

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

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

    fclose($handle);
})->chunk(4)->map(function (array $lines) {
    return LogEntry::fromLines($lines);
})->each(function (LogEntry $logEntry) {
    // Process the log entry...
});

再比如,假设你需要遍历 10,000 个 Eloquent model。使用传统 Laravel 集合时,这 10,000 个 Eloquent model 必须同时加载到内存中:

php
use App\Models\User;

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

而 query builder 的 cursor 方法会返回一个 LazyCollection 实例。这使你既可以只对数据库执行一次查询,又可以在任意时刻只将一个 Eloquent model 保留在内存中。在这个例子中,filter 回调只有在我们真正逐个迭代用户时才会执行,因此内存占用会大幅降低:

php
use App\Models\User;

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

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

创建惰性集合

要创建惰性集合实例,你应将一个 PHP generator 函数传给集合的 make 方法:

php
use Illuminate\Support\LazyCollection;

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

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

    fclose($handle);
});

Enumerable Contract

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

WARNING

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

惰性集合方法

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

takeUntilTimeout() {.collection-method}

takeUntilTimeout 方法会返回一个新的惰性集合,它会持续枚举值直到指定时间。超过该时间后,集合就会停止枚举:

php
$lazyCollection = LazyCollection::times(INF)
    ->takeUntilTimeout(now()->plus(minutes: 1));

$lazyCollection->each(function (int $number) {
    dump($number);

    sleep(1);
});

// 1
// 2
// ...
// 58
// 59

为了说明这个方法的用法,假设某个应用程序通过 cursor 从数据库中提交发票。你可以定义一个每 15 分钟运行一次的计划任务,并且每次最多只处理 14 分钟的发票:

php
use App\Models\Invoice;
use Illuminate\Support\Carbon;

Invoice::pending()->cursor()
    ->takeUntilTimeout(
        Carbon::createFromTimestamp(LARAVEL_START)->add(14, 'minutes')
    )
    ->each(fn (Invoice $invoice) => $invoice->submit());

tapEach() {.collection-method}

each 方法会立刻对集合中的每个项目调用给定回调,而 tapEach 方法则只会在项目被逐个从列表中取出时调用该回调:

php
// Nothing has been dumped so far...
$lazyCollection = LazyCollection::times(INF)->tapEach(function (int $value) {
    dump($value);
});

// Three items are dumped...
$array = $lazyCollection->take(3)->all();

// 1
// 2
// 3

throttle() {.collection-method}

throttle 方法会对惰性集合进行节流,使每个值都在指定秒数后才返回。这个方法在你与会对传入请求进行速率限制的外部 API 交互时尤其有用:

php
use App\Models\User;

User::where('vip', true)
    ->cursor()
    ->throttle(seconds: 1)
    ->each(function (User $user) {
        // Call external API...
    });

remember() {.collection-method}

remember 方法会返回一个新的惰性集合,它会记住已经枚举过的任何值,并且在后续枚举集合时不会再次获取这些值:

php
// No query has been executed yet...
$users = User::cursor()->remember();

// The query is executed...
// The first 5 users are hydrated from the database...
$users->take(5)->all();

// First 5 users come from the collection's cache...
// The rest are hydrated from the database...
$users->take(20)->all();

withHeartbeat() {.collection-method}

withHeartbeat 方法允许你在惰性集合被枚举期间按固定时间间隔执行一个回调。这对于需要定期执行维护任务的长时间运行操作特别有用,例如续期锁或发送进度更新:

php
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\Cache;

$lock = Cache::lock('generate-reports', seconds: 60 * 5);

if ($lock->get()) {
    try {
        Report::where('status', 'pending')
            ->lazy()
            ->withHeartbeat(
                CarbonInterval::minutes(4),
                fn () => $lock->extend(CarbonInterval::minutes(5))
            )
            ->each(fn ($report) => $report->process());
    } finally {
        $lock->release();
    }
}