geniv/nette-collection

此包已被废弃,不再维护。未建议替代包。

Nette 框架的集合类

v1.0.1 2019-08-29 15:20 UTC

This package is auto-updated.

Last update: 2021-11-29 02:48:55 UTC


README

受启发于: https://github.com/tightenco/collect

文档: https://laravel.net.cn/docs/5.8/collections

安装

$ composer require geniv/nette-collection

"geniv/nette-collection": "^1.0"

require

"php": ">=7.0"

简介

Collection\Collection 类为处理数据数组提供了一个流畅、便捷的包装器。例如,看看下面的代码。我们将使用 collect 助手从数组创建一个新的集合实例,对每个元素执行 strtoupper 函数,然后删除所有空元素

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

如你所见,Collection 类允许你链式调用其方法以执行底层数组的流畅映射和缩减。一般来说,每个 Collection 方法都返回一个全新的 Collection 实例。

创建集合

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

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

可用方法

use Collection\Collection;

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

您可以从下表中选择任何方法,以查看其用法示例

方法 ... ...
all isNotEmpty slice
average join some
avg keyBy sort
chunk keys sortBy
collapse last sortByDesc
combine macro sortKeys
concat make sortKeysDesc
contains map splice
containsStrict mapInto split
count mapSpread sum
countBy mapToGroups take
crossJoin mapWithKeys tap
dd max times
diff median toArray
diffAssoc merge toJson
diffKeys mergeRecursive transform
dump min union
duplicates mode unique
duplicatesStrict nth uniqueStrict
each only unless
eachSpread pad unlessEmpty
every partition unlessNotEmpty
except pipe unwrap
filter pluck values
first pop when
firstWhere prepend whenEmpty
flatMap pull whenNotEmpty
flatten push where
flip put whereStrict
forget random whereBetween
forPage reduce whereIn
get reject whereInStrict
groupBy replace whereInstanceOf
has replaceRecursive whereNotBetween
implode reverse whereNotIn
intersect search whereNotInStrict
intersectByKeys shift wrap
isEmpty shuffle zip

方法列表

all()

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

Collection::make([1, 2, 3])->all();

// [1, 2, 3]

average()

average方法的别名。

avg()

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

$average = Collection::make([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');

// 20

$average = Collection::make([1, 1, 2, 4])->avg();

// 2

chunk()

chunk方法将集合分割成多个指定大小的较小集合

$collection = Collection::make([1, 2, 3, 4, 5, 6, 7]);

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

$chunks->toArray();

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

此方法在处理类似于Bootstrap的网格系统时特别有用。想象一下,您有一个Eloquent模型集合,想要在网格中显示

@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方法将数组集合压缩成一个单一的扁平集合

$collection = Collection::make([[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方法将集合的值(作为键)与另一个数组或集合的值合并

$collection = Collection::make(['name', 'age']);

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

$combined->all();

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

concat()

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

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

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

$concatenated->all();

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

contains()

contains方法确定集合中是否包含给定项

$collection = Collection::make(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');

// true

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

// false

您还可以向contains方法传递一个键/值对,以确定该对是否存在于集合中

$collection = Collection::make([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

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

// false

最后,您还可以向contains方法传递一个回调,以执行自己的真值测试

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

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

// false

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

containsStrict()

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

count()

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

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

$collection->count();

// 4

countBy()

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

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

$counted = $collection->countBy();

$counted->all();

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

然而,您可以向countBy方法传递一个回调以按自定义值计算所有项

$collection = Collection::make(['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方法将集合的值与给定的数组或集合中的值交叉连接,返回一个笛卡尔积,具有所有可能的排列

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

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

$matrix->all();

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

$collection = Collection::make([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方法转储集合的项并结束脚本的执行

$collection = Collection::make(['John Doe', 'Jane Doe']);

$collection->dd();

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

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

diff()

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

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

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

$diff->all();

// [1, 3, 5]

diffAssoc()

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

$collection = Collection::make([
    '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数组进行比较。此方法将返回原始集合中不存在于给定集合中的键/值对。

$collection = Collection::make([
    '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 方法输出集合的项。

$collection = Collection::make(['John Doe', 'Jane Doe']);

$collection->dump();

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

如果您想在输出集合后停止脚本执行,请使用 dd 方法代替。

duplicates()

duplicates 方法检索并返回集合中的重复值。

$collection = Collection::make(['a', 'b', 'a', 'c', 'b']);

$collection->duplicates();

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

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

$employees = Collection::make([
    ['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 方法遍历集合中的项,并将每个项传递给回调函数。

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

如果您想停止遍历项,可以在回调函数中返回 false。

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

eachSpread()

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

$collection = Collection::make([['John Doe', 35], ['Jane Doe', 33]]);

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

您可以通过从回调函数中返回 false 来停止遍历项。

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

every()

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

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

// false

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

$collection = Collection::make([]);

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

// true

except()

except 方法返回集合中除了指定键之外的各项。

$collection = Collection::make(['product_id' => 1, 'price' => 100, 'discount' => false]);

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

$filtered->all();

// ['product_id' => 1]

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

filter()

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

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

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

$filtered->all();

// [3, 4]

如果没有提供回调函数,则将移除集合中所有等同于 false 的条目。

$collection = Collection::make([1, 2, 3, null, false, '', 0, []]);

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

// [1, 2, 3]

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

first()

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

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

// 3

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

Collection::make([1, 2, 3, 4])->first();

// 1

firstWhere()

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

$collection = Collection::make([
    ['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方法

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

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

与where方法类似,您可以将一个参数传递给firstWhere方法。在这种情况下,firstWhere方法将返回第一个给定项键的值为"truthy"的项

$collection->firstWhere('age');

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

flatMap()

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

$collection = Collection::make([
    ['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方法将多维集合扁平化为单维

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

$flattened = $collection->flatten();

$flattened->all();

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

您可以可选地传递一个"depth"参数给函数

$collection = Collection::make([
    '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方法交换集合的键与其对应的值

$collection = Collection::make(['name' => 'taylor', 'framework' => 'laravel']);

$flipped = $collection->flip();

$flipped->all();

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

forget()

forget方法通过键从集合中删除项

$collection = Collection::make(['name' => 'taylor', 'framework' => 'laravel']);

$collection->forget('name');

$collection->all();

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

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

forPage()

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

$collection = Collection::make([1, 2, 3, 4, 5, 6, 7, 8, 9]);

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

$chunk->all();

// [4, 5, 6]

get()

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

$collection = Collection::make(['name' => 'taylor', 'framework' => 'laravel']);

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

// taylor

您可以选择传递一个默认值作为第二个参数

$collection = Collection::make(['name' => 'taylor', 'framework' => 'laravel']);

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

// default-value

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

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

// default-value

groupBy()

groupBy方法根据给定的键对集合的项进行分组

$collection = Collection::make([
    ['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'],
        ],
    ]
*/

您可以通过传递一个回调而不是字符串键。该回调应返回您希望用作分组的值

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

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

$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方法确定给定的键是否存在于集合中

$collection = Collection::make(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);

$collection->has('product');

// true

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

// true

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

// false

implode()

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

$collection = Collection::make([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
]);

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

// Desk, Chair

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

Collection::make([1, 2, 3, 4, 5])->implode('-');

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

intersect()

交集方法会从原始集合中移除给定数组或集合中不存在的任何值。结果集合将保留原始集合的键

$collection = Collection::make(['Desk', 'Sofa', 'Chair']);

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

$intersect->all();

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

intersectByKeys()

intersectByKeys方法会移除原始集合中不在给定数组或集合中存在的任何键

$collection = Collection::make([
    '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

Collection::make([])->isEmpty();

// true

isNotEmpty()

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

Collection::make([])->isNotEmpty();

// false

join()

join方法使用字符串将集合的值连接起来

Collection::make(['a', 'b', 'c'])->join(', '); // 'a, b, c'
Collection::make(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c'
Collection::make(['a', 'b'])->join(', ', ' and '); // 'a and b'
Collection::make(['a'])->join(', ', ' and '); // 'a'
Collection::make([])->join(', ', ' and '); // ''

keyBy()

keyBy方法使用给定的键对集合进行索引。如果多个项目具有相同的键,则新集合中只会出现最后一个

$collection = Collection::make([
    ['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'],
    ]
*/

您还可以向方法传递一个回调函数。回调函数应该返回用于索引集合的值

$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方法返回集合的所有键

$collection = Collection::make([
    '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方法返回集合中通过给定真值测试的最后一个元素

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

// 2

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

Collection::make([1, 2, 3, 4])->last();

// 4

macro()

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

make()

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

map()

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

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

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

$multiplied->all();

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

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

mapInto()

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

class Currency
{
    /**
     * Create a new currency instance.
     *
     * @param  string  $code
     * @return void
     */
    function __construct(string $code)
    {
        $this->code = $code;
    }
}

$collection = Collection::make(['USD', 'EUR', 'GBP']);

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

$currencies->all();

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

mapSpread()

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

$collection = Collection::make([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方法根据给定的回调函数对集合的项进行分组。回调函数应返回一个包含单个键/值对的关联数组,从而形成一个新的分组值的集合

$collection = Collection::make([
    [
        '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 方法遍历集合,并将每个值传递给给定的回调函数。回调函数应返回一个包含单个键/值对的关联数组

$collection = Collection::make([
    [
        '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 方法返回给定键的最大值

$max = Collection::make([['foo' => 10], ['foo' => 20]])->max('foo');

// 20

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

// 5

median()

median 方法返回给定键的中值

$median = Collection::make([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');

// 15

$median = Collection::make([1, 1, 2, 4])->median();

// 1.5

merge()

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

$collection = Collection::make(['product_id' => 1, 'price' => 100]);

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

$merged->all();

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

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

$collection = Collection::make(['Desk', 'Chair']);

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

$merged->all();

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

mergeRecursive()

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

$collection = Collection::make(['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 方法返回给定键的最小值

$min = Collection::make([['foo' => 10], ['foo' => 20]])->min('foo');

// 10

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

// 1

mode()

mode 方法返回给定键的众数

$mode = Collection::make([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');

// [10]

$mode = Collection::make([1, 1, 2, 4])->mode();

// [1]

nth()

nth 方法创建一个新的集合,其中包含每第 n 个元素

$collection = Collection::make(['a', 'b', 'c', 'd', 'e', 'f']);

$collection->nth(4);

// ['a', 'e']

您可以可选地传递偏移量作为第二个参数

$collection->nth(4, 1);

// ['b', 'f']

only()

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

$collection = Collection::make(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

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

$filtered->all();

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

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

pad()

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

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

$collection = Collection::make(['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 函数结合使用,以分离通过给定真值测试的元素和未通过测试的元素

$collection = Collection::make([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 方法将集合传递给给定的回调函数并返回结果

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

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

// 6

pluck()

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

$collection = Collection::make([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);

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

$plucked->all();

// ['Desk', 'Chair']

您还可以指定您希望结果集合如何键控

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

$plucked->all();

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

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

$collection = Collection::make([
    ['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 方法从集合中删除并返回最后一个元素

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

$collection->pop();

// 5

$collection->all();

// [1, 2, 3, 4]

prepend()

prepend() 方法向集合的开始位置添加一个项目

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

$collection->prepend(0);

$collection->all();

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

您还可以传递第二个参数来设置被添加项目的键

$collection = Collection::make(['one' => 1, 'two' => 2]);

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

$collection->all();

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

pull()

pull() 方法通过键从集合中移除并返回一个项目

$collection = Collection::make(['product_id' => 'prod-100', 'name' => 'Desk']);

$collection->pull('name');

// 'Desk'

$collection->all();

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

push()

push() 方法将一个项目添加到集合的末尾

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

$collection->push(5);

$collection->all();

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

put()

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

$collection = Collection::make(['product_id' => 1, 'name' => 'Desk']);

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

$collection->all();

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

random()

random() 方法从集合中返回一个随机项目

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

$collection->random();

// 4 - (retrieved randomly)

您可以选择传递一个整数给random,以指定您想要随机检索的项目数量。如果您显式地传递了希望接收的项目数量,则总是返回一个项目集合

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

$random->all();

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

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

reduce()

reduce() 方法将集合减少到单个值,将每次迭代的结果传递给后续迭代

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

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

// 6

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

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

// 10

reject()

reject() 方法使用给定的回调过滤集合。回调应返回 true 如果项目应从结果集合中删除

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

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

$filtered->all();

// [1, 2]

关于reject方法的逆操作,请参阅filter方法。

replace()

replace() 方法的行为类似于merge;但是,除了用字符串键覆盖匹配的项目外,replace方法还将覆盖集合中具有匹配数字键的项目

$collection = Collection::make(['Taylor', 'Abigail', 'James']);

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

$replaced->all();

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

replaceRecursive()

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

$collection = Collection::make(['Taylor', 'Abigail', ['James', 'Victoria', 'Finn']]);

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

$replaced->all();

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

reverse()

reverse() 方法反转集合项的顺序,同时保留原始键

$collection = Collection::make(['a', 'b', 'c', 'd', 'e']);

$reversed = $collection->reverse();

$reversed->all();

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

search()

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

$collection = Collection::make([2, 4, 6, 8]);

$collection->search(4);

// 1

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

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

// false

或者,您可以传递自己的回调来搜索第一个通过您真实性测试的项目

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

// 2

shift()

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

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

$collection->shift();

// 1

$collection->all();

// [2, 3, 4, 5]

shuffle()

shuffle() 方法随机打乱集合中的项目

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

$shuffled = $collection->shuffle();

$shuffled->all();

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

slice()

slice() 方法返回从给定索引开始的集合的一部分

$collection = Collection::make([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

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

$slice->all();

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

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

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

$slice->all();

// [5, 6]

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

some()

contains方法的别名。

sort()

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

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

$sorted = $collection->sort();

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

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

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

如果需要排序嵌套数组或对象的集合,请参阅sortBy和sortByDesc方法。

sortBy()

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

$collection = Collection::make([
    ['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],
    ]
*/

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

$collection = Collection::make([
    ['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方法根据底层关联数组的键对集合进行排序

$collection = Collection::make([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
]);

$sorted = $collection->sortKeys();

$sorted->all();

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

sortKeysDesc()

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

splice()

splice方法从指定的索引开始删除并返回一个项切片

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

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

$chunk->all();

// [3, 4, 5]

$collection->all();

// [1, 2]

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

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

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

$chunk->all();

// [3]

$collection->all();

// [1, 2, 4, 5]

此外,您还可以传递一个包含新项目的第三个参数以替换从集合中删除的项目

$collection = Collection::make([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方法将集合拆分为给定数量的组

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

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

$groups->toArray();

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

sum()

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

Collection::make([1, 2, 3, 4, 5])->sum();

// 15

如果集合包含嵌套数组或对象,您应该传递一个键以用于确定要相加的值

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

$collection->sum('pages');

// 1272

此外,您还可以传递自己的回调来确定要相加的集合值

$collection = Collection::make([
    ['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方法返回一个新的集合,其中包含指定数量的项目

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

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

$chunk->all();

// [0, 1, 2]

您还可以传递一个负整数,从集合的末尾取出指定数量的项目

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

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

$chunk->all();

// [4, 5]

tap()

tap方法将集合传递给给定的回调,允许您在特定点“触摸”集合并对项目进行操作,而不会影响集合本身

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

// 1

times()

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

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

$collection->all();

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

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

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

$categories->all();

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

toArray()

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

$collection = Collection::make(['name' => 'Desk', 'price' => 200]);

$collection->toArray();

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

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

toJson()

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

$collection = Collection::make(['name' => 'Desk', 'price' => 200]);

$collection->toJson();

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

transform()

transform 方法遍历集合,并对集合中的每个项目调用给定的回调函数。集合中的项目将由回调函数返回的值替换。

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

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

$collection->all();

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

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

union()

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

$collection = Collection::make([1 => ['a'], 2 => ['b']]);

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

$union->all();

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

unique()

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

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

$unique = $collection->unique();

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

// [1, 2, 3, 4]

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

$collection = Collection::make([
    ['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 = $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 方法使用“严格”比较进行筛选。

uniqueStrict()

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

unless()

unless 方法将执行给定的回调,除非该方法给出的第一个参数评估为 true。

$collection = Collection::make([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()

whenNotEmpty 方法的别名。

unlessNotEmpty()

whenEmpty 方法的别名。

unwrap()

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

Collection::unwrap(Collection::make('John Doe'));

// ['John Doe']

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

// ['John Doe']

Collection::unwrap('John Doe');

// 'John Doe'

values()

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

$collection = Collection::make([
    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()

当该方法给出的第一个参数评估为 true 时,when 方法将执行给定的回调。

$collection = Collection::make([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方法会在集合为空时执行给定的回调函数。

$collection = Collection::make(['michael', 'tom']);

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

$collection->all();

// ['michael', 'tom']

$collection = Collection::make();

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

$collection->all();

// ['adam']

$collection = Collection::make(['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方法会在集合不为空时执行给定的回调函数。

$collection = Collection::make(['michael', 'tom']);

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

$collection->all();

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

$collection = Collection::make();

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

$collection->all();

// []

$collection = Collection::make();

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

$collection->all();

// ['taylor']

关于whenNotEmpty的相反方法,请参阅whenEmpty方法。

where()

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

$collection = Collection::make([
    ['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方法。

whereStrict()

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

whereBetween()

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

$collection = Collection::make([
    ['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方法通过给定的键/值过滤集合,该键/值包含在给定的数组中。

$collection = Collection::make([
    ['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' => 'Bookcase', 'price' => 150],
        ['product' => 'Desk', 'price' => 200],
    ]
*/

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

whereInStrict()

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

whereInstanceOf()

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

$collection = Collection::make([
    new User,
    new User,
    new Post,
]);

return $collection->whereInstanceOf(User::class);

whereNotBetween()

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

$collection = Collection::make([
    ['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方法通过给定的键/值过滤集合,该键/值不包含在给定的数组中。

$collection = Collection::make([
    ['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方法的签名相同;然而,所有值都使用“严格”比较进行比较。

wrap()

静态wrap方法在适用时将给定的值包裹在集合中。

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

$collection->all();

// ['John Doe']

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

$collection->all();

// ['John Doe']

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

$collection->all();

// ['John Doe']

zip()

zip方法将给定数组中的值与原始集合中相应索引的值合并。

$collection = Collection::make(['Chair', 'Desk']);

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

$zipped->all();

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

高阶消息

集合还提供了对“高阶消息”的支持,这些是执行集合上常见操作的快捷方式。提供高阶消息的集合方法是:average、avg、contains、each、every、filter、first、flatMap、groupBy、keyBy、map、max、min、partition、reject、some、sortBy、sortByDesc、sum和unique。

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

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

$users->each->markAsVip();

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

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

return $users->sum->votes;