教程 > laravel 教程 > 阅读:120

laravel 集合可用函数 二——迹忆客-ag捕鱼王app官网

集合方法 二

laravel 集合可用方法 一中 介绍了部分的集合中可用的方法,本节继续介绍剩下的方法

isempty()

如果集合为空的话 isempty 方法返回 true;否则返回 false:

collect([])->isempty();
// true

isnotempty()

如果集合不为空的话 isnotempty 方法返回 true;否则返回 false:

collect([])->isnotempty();
// false

join()

join 方法用于将集合值通过字符串连接起来:

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

keyby()

keyby 方法将指定键的值作为集合的键,如果多个数据项拥有同一个键,只有最后一个会出现在新集合里面:

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

你还可以传递自己的回调到该方法,该回调将会返回经过处理的键的值作为新的集合键:

$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 = collect([
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'chair'],
]);
$keys = $collection->keys();
$keys->all();
// ['prod-100', 'prod-200']

last()

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

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

还可以调用无参的 last 方法来获取集合的最后一个元素。如果集合为空。返回 null:

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

macro()

静态 macro 方法允许你在运行时添加方法到 collection 类,更多细节可以查看扩展集合部分文档。

make()

静态 make 方法会创建一个新的集合实例,细节可查看创建集合部分文档。

map()

map 方法遍历集合并传递每个值给给定回调。该回调可以修改数据项并返回,从而生成一个新的经过修改的集合:

$collection = collect([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 = collect(['usd', 'eur', 'gbp']);
​
$currencies = $collection->mapinto(currency::class);
​
$currencies->all();
​
// [currency('usd'), currency('eur'), currency('gbp')]

mapspread()

mapspread 方法会迭代集合项,传递每个嵌套集合项值到给定回调。在回调中我们可以修改集合项并将其返回,从而通过修改的值组合成一个新的集合:

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

maptogroups()

maptogroups 方法会通过给定回调对集合项进行分组,回调会返回包含单个键值对的关联数组,从而将分组后的值组合成一个新的集合:

$collection = collect([
    [
        'name' => 'john doe',
        'department' => 'sales',
    ],
    [
        'name' => 'jane doe',
        'department' => 'sales',
    ],
    [
        'name' => 'johnny doe',
        'department' => 'marketing',
    ]
]);
​
$grouped = $collection->maptogroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
});
​
$grouped->toarray();
​
/*
    [
        'sales' => ['john doe', 'jane doe'],
        'marketing' => ['johhny doe'],
    ]
*/
​
$grouped->get('sales')->all();
​
// ['john doe', 'jane doe']

mapwithkeys()

mapwithkeys 方法对集合进行迭代并传递每个值到给定回调,该回调会返回包含键值对的关联数组:

$collection = collect([
    [
        'name' => 'john',
        'department' => 'sales',
        'email' => 'john@example.com'
    ],
    [
        'name' => 'jane',
        'department' => 'marketing',
        'email' => 'jane@example.com'
    ]
]);
​
$keyed = $collection->mapwithkeys(function ($item) {
    return [$item['email'] => $item['name']];
});
​
$keyed->all();
/*
[
    'john@example.com' => 'john',
    'jane@example.com' => 'jane',
]
*/

max()

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

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

median()

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

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

merge()

merge 方法合并给定数组到集合。该数组中的任何字符串键匹配集合中的字符串键的将会重写集合中的值:

$collection = collect(['product_id' => 1, 'name' => 'desk']);
$merged = $collection->merge(['price' => 100, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'name' => 'desk', 'price' => 100, 'discount' => false]

如果给定数组的键是数字,数组的值将会附加到集合后面:

$collection = collect(['desk', 'chair']);
$merged = $collection->merge(['bookcase', 'door']);
$merged->all();
// ['desk', 'chair', 'bookcase', 'door']

mergerecursive()

mergerecursive() 方法会递归合并给定数组或集合到原来的集合,如果给定项中的某个字符串键和原集合中的字符串键匹配,那么这些键对应的值就会被合并到一个数组中,而且这个操作是递归的:

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

min()

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

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

mode()

mode 方法会返回给定键的众数:

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

nth()

nth方法组合集合中第 n-th 个元素创建一个新的集合:

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

还可以传递一个 offset(偏移位置)作为第二个参数:

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

only()

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

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

注:该方法的行为会在使用 eloquent 集合时发生改变。

pad()

pad 方法将给定值填充数组直到达到指定的最大长度。该方法和 php 函数 array_pad 类似。

如果你想要把数据填充到左侧,需要指定一个负值长度,如果指定长度绝对值小于等于数组长度那么将不会做任何填充:

$collection = collect(['a', 'b', 'c']);
$filtered = $collection->pad(5, 0);
$filtered->all();
// ['a', 'b', 'c', 0, 0]
$filtered = $collection->pad(-5, 0);
$filtered->all();
// [0, 0, 'a', 'b', 'c']

partition()

partition 方法可以和 php 函数 list 一起使用,从而将通过真理测试和没通过的分割开来:

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

pipe()

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

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

pluck()

pluck 方法为给定键获取所有集合值:

$collection = collect([
    ['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']

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

$collection = collect([
    ['brand' => 'tesla',  'color' => 'red'],
    ['brand' => 'pagani', 'color' => 'white'],
    ['brand' => 'tesla',  'color' => 'black'],
    ['brand' => 'pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['tesla' => 'black', 'pagani' => 'orange']

pop()

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

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

prepend()

prepend 方法添加数据项到集合开头:

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

你还可以传递第二个参数到该方法用于设置前置项的键:

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

pull()

pull 方法通过键从集合中移除并返回数据项:

$collection = collect(['product_id' => 'prod-100', 'name' => 'desk']);
​
$collection->pull('name');
​
// 'desk'
​
$collection->all();
​
// ['product_id' => 'prod-100']

push()

push 方法附加数据项到集合结尾:

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

put()

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

$collection = collect(['product_id' => 1, 'name' => 'desk']);
​
$collection->put('price', 100);
​
$collection->all();
​
// ['product_id' => 1, 'name' => 'desk', 'price' => 100]

random()

random 方法从集合中返回随机数据项:

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

我们可以传递一个整型数据到 random 函数来指定返回的数据数目,如果该整型数值大于1,将会返回一个集合:

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

如果集合中的元素个数小于请求的随机数,该方法会抛出 invalidargumentexception 异常。

reduce()

reduce 方法用于减少集合到单个值,传递每个迭代结果到子迭代:

$collection = collect([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 = collect([1, 2, 3, 4]);
$filtered = $collection->reject(function ($value, $key) {
    return $value > 2;
});
$filtered->all();
// [1, 2]

和 reject 方法相对的方法是 filter 方法。

replace()

replace 方法和 merge 方法有点像,不过,除了通过字符串键覆盖匹配项之外,replace 方法还会覆盖集合中匹配的数字键:

$collection = collect(['taylor', 'abigail', 'james']);
​
$replaced = $collection->replace([1 => 'victoria', 3 => 'finn']);
​
$replaced->all();
​
// ['taylor', 'victoria', 'james', 'finn']

replacerecursive()

该方法和 replace 方法类似,但是它会递归数组并应用同样的替换逻辑到内部值:

$collection = collect(['taylor', 'abigail', ['james', 'victoria', 'finn']]);
​
$replaced = $collection->replacerecursive(['charlie', 2 => [1 => 'king']]);
​
$replaced->all();
​
// ['charlie', 'abigail', ['james', 'king', 'finn']]

reverse()

reverse 方法将集合数据项的顺序颠倒:

$collection = collect(['a', 'b', 'c', 'd', 'e']);
​
$reversed = $collection->reverse();
​
$reversed->all();
​
/*
    [
        4 => 'e',
        3 => 'd',
        2 => 'c',
        1 => 'b',
        0 => 'a',
    ]
*/

search 方法为给定值查询集合,如果找到的话返回对应的键,如果没找到,则返回 false:

$collection = collect([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 = collect([1, 2, 3, 4, 5]);
​
$collection->shift();
​
// 1
​
$collection->all();
​
// [2, 3, 4, 5]

shuffle()

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

$collection = collect([1, 2, 3, 4, 5]);
​
$shuffled = $collection->shuffle();
​
$shuffled->all();
// [3, 2, 5, 1, 4] // (随机生成)

skip()

skip 方法返回一个新的跳过给定数据项的集合:

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

slice()

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

$collection = collect([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 = collect([5, 3, 1, 2, 4]);
​
$sorted = $collection->sort();
​
$sorted->values()->all();
​
// [1, 2, 3, 4, 5]

如果你需要更加高级的排序,你可以给sort方法传递一个回调函数,里面定义自己的算法。参考 php 官方文档关于 uasort 的说明,sort 方法底层正是调用了该方法。

注:要为嵌套集合和对象排序,查看 sortby 和 sortbydesc 方法。

sortdesc()

该方法和 sort 方法签名一样,但是会以相反顺序对集合进行排序:

$collection = collect([5, 3, 1, 2, 4]);
​
$sorted = $collection->sortdesc();
​
$sorted->values()->all();
​
// [5, 4, 3, 2, 1]

sortby()

sortby 方法通过给定键对集合进行排序, 排序后的集合保持原有数组索引,在本例中,使用 values 方法重置键为连续索引:

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

你还可以传递自己的回调来判断如何排序集合的值:

$collection = collect([
    ['name' => 'desk', 'colors' => ['black', 'mahogany']],
    ['name' => 'chair', 'colors' => ['black']],
    ['name' => 'bookcase', 'colors' => ['red', 'beige', 'brown']],
]);
​
$sorted = $collection->sortby(function ($product, $key) {
    return count($product['colors']);
});
​
$sorted->values()->all();
​
/*
    [
        ['name' => 'chair', 'colors' => ['black']],
        ['name' => 'desk', 'colors' => ['black', 'mahogany']],
        ['name' => 'bookcase', 'colors' => ['red', 'beige', 'brown']],
    ]
*/

sortbydesc()

该方法和 sortby 用法相同,不同之处在于按照相反顺序进行排序。

sortkeys()

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

$collection = collect([
    'id' => 22345,
    'first' => 'john',
    'last' => 'doe',
]);
​
$sorted = $collection->sortkeys();
​
$sorted->all();
​
/*
    [
        'first' => 'john',
        'id' => 22345,
        'last' => 'doe',
    ]
*/

sortkeysdesc()

该方法和 sortkeys 方法方法签名相同,但是排序顺序与其相反。

splice()

splice 方法从给定位置开始移除并返回数据项切片:

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

你可以传递参数来限制返回组块的大小:

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

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

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

split()

split 方法通过给定数值对集合进行分组:

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

sum()

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

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

如果集合包含嵌套数组或对象,应该传递一个键用于判断对哪些值进行求和运算:

$collection = collect([
    ['name' => 'javascript: the good parts', 'pages' => 176],
    ['name' => 'javascript: the definitive guide', 'pages' => 1096],
]);
​
$collection->sum('pages');
​
// 1272

此外,你还可以传递自己的回调来判断对哪些值进行求和:

$collection = collect([
    ['name' => 'chair', 'colors' => ['black']],
    ['name' => 'desk', 'colors' => ['black', 'mahogany']],
    ['name' => 'bookcase', 'colors' => ['red', 'beige', 'brown']],
]);
​
$collection->sum(function ($product) {
    return count($product['colors']);
});
// 6

take()

take 方法使用指定数目的数据项返回一个新的集合:

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

你还可以传递负数的方式从集合末尾开始获取指定数目的数据项:

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

tap()

tap 方法会传递集合到给定回调,从而允许你在指定入口进入集合并对集合项进行处理而不影响集合本身:

collect([2, 4, 3, 1, 5])
    ->sort()
    ->tap(function ($collection) {
        log::debug('values after sorting', $collection->values()->toarray());
    })
    ->shift();
​
// 1

times()

times 方法是collection中的一个静态方法,第一个参数是一个整数,表示元素的个数。第二个参数是一个回调函数,该回调函数的参数是由第一个参数产生的,依次对第一个参数减去1,看下面的例子:

$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 #'.$number]);
});
​
$categories->all();
​
/*
    [
        ['id' => 1, 'name' => 'category #1'],
        ['id' => 2, 'name' => 'category #2'],
        ['id' => 3, 'name' => 'category #3'],
    ]
*/

toarray()

toarray 方法将集合转化为一个原生的 php 数组。如果集合的值是 eloquent 模型,该模型也会被转化为数组:

$collection = collect(['name' => 'desk', 'price' => 200]);
​
$collection->toarray();
​
/*
    [
        ['name' => 'desk', 'price' => 200],
    ]
*/

注:toarray 还会将所有 arrayable 实例嵌套对象集合转化为数组。如果你想要获取底层数组,使用 all 方法。

tojson()

tojson 方法将集合转化为 json:

$collection = collect(['name' => 'desk', 'price' => 200]);
​
$collection->tojson();
​
// '{"name":"desk","price":200}'

transform()

transform 方法迭代集合并对集合中每个数据项调用给定回调。集合中的数据项将会被替代成从回调中返回的值:

$collection = collect([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 = collect([1 => ['a'], 2 => ['b']]);
​
$union = $collection->union([3 => ['c'], 1 => ['b']]);
​
$union->all();
​
// [1 => ['a'], 2 => ['b'], [3 => ['c']]

unique()

unique 方法返回集合中所有的唯一数据项, 返回的集合保持原来的数组键,在本例中我们使用 values 方法重置这些键为连续的数字索引 :

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

处理嵌套数组或对象时,可以指定用于判断唯一的键:

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

注:该方法的行为会在使用 eloquent 集合时发生改变。

uniquestrict()

该方法和 unique 方法签名一样,不同之处在于所有值都是「严格」比较。

unless()

unless 方法会执行给定回调,除非传递到该方法的第一个参数等于 true:

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

与 unless 相对的方法是 when方法。

unlessempty()

whennotempty 方法的别名。

unlessnotempty()

whenempty 方法的别名。

unwrap()

静态 unwrap 方法会从给定值中返回集合项:

collection::unwrap(collect('john doe'));
// ['john doe']
collection::unwrap(['john doe']);
// ['john doe']
collection::unwrap('john doe');
// 'john doe'

values()

values 方法通过将集合键重置为连续整型数字的方式返回新的集合:

$collection = collect([
    10 => ['product' => 'desk', 'price' => 200],
    11 => ['product' => 'desk', 'price' => 200]
]);
$values = $collection->values();
$values->all();
/*
    [
        0 => ['product' => 'desk', 'price' => 200],
        1 => ['product' => 'desk', 'price' => 200],
    ]
*/

when()

when方法在传入的第一个参数执行结果为 true 时执行给定回调:

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

与 when 方法相对的是 unless。

whenempty()

当集合为空时,whenempty 方法会执行给定回调:

$collection = collect(['michael', 'tom']);
​
$collection->whenempty(function ($collection) {
    return $collection->push('adam');
});
​
$collection->all();
​
// ['michael', 'tom']
​
$collection = collect();
​
$collection->whenempty(function ($collection) {
    return $collection->push('adam');
});
​
$collection->all();
​
// ['adam']
​
$collection = collect(['michael', 'tom']);
​
$collection->whenempty(function($collection) {
    return $collection->push('adam');
}, function($collection) {
    return $collection->push('taylor');
});
​
$collection->all();
​
// ['michael', 'tom', 'taylor']

与 whenempty 相对的方法是 whennotempty。

whennotempty()

当集合不为空时,whennotempty 方法会执行给定回调:

$collection = collect(['michael', 'tom']);
​
$collection->whennotempty(function ($collection) {
    return $collection->push('adam');
});
​
$collection->all();
​
// ['michael', 'tom', 'adam']
​
$collection = collect();
​
$collection->whennotempty(function ($collection) {
    return $collection->push('adam');
});
​
$collection->all();
​
// []
​
$collection = collect();
​
$collection->whennotempty(function($collection) {
    return $collection->push('adam');
}, function($collection) {
    return $collection->push('taylor');
});
​
$collection->all();
​
// ['taylor']

与 whennotempty 相对的方法是 whenempty。

where()

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

$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 方法使用「严格」比较进行过滤。

作为可选项,你可以传递比较操作符作为 where 方法的第二个参数:

$collection = collect([
    ['name' => 'jim', 'deleted_at' => '2019-01-01 00:00:00'],
    ['name' => 'sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ['name' => 'sue', 'deleted_at' => null],
]);
​
$filtered = $collection->where('deleted_at', '!=', null);
​
$filtered->all();
​
/*
    [
        ['name' => 'jim', 'deleted_at' => '2019-01-01 00:00:00'],
        ['name' => 'sally', 'deleted_at' => '2019-01-02 00:00:00'],
    ]
*/

wherestrict()

该方法和 where 用法签名一样,不同之处在于,所有值都使用「严格」比较。

wherebetween()

wherebetween 方法通过给定范围过滤集合:

$collection = collect([
    ['product' => 'desk', 'price' => 200],
    ['product' => 'chair', 'price' => 80],
    ['product' => 'bookcase', 'price' => 150],
    ['product' => 'pencil', 'price' => 30],
    ['product' => 'door', 'price' => 100],
]);
​
$filtered = $collection->wherebetween('price', [100, 200]);
​
$filtered->all();
​
/*
    [
        ['product' => 'desk', 'price' => 200],
        ['product' => 'bookcase', 'price' => 150],
        ['product' => 'door', 'price' => 100],
    ]
*/

wherein()

wherein 方法通过包含在给定数组中的键值对集合进行过滤:

$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' => 'bookcase', 'price' => 150],
    ['product' => 'desk', 'price' => 200],
]
*/

wherein 方法在检查数据项值的时候使用「宽松」比较,要使用「严格」比较可以使用 whereinstrict 方法。

whereinstrict()

该方法和 wherein 方法签名相同,不同之处在于 whereinstrict 在比较值的时候使用「严格」比较。

whereinstanceof()

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

$collection = collect([
    new user,
    new user,
    new post,
]);
​
return $collection->whereinstanceof(user::class);

wherenotbetween()

wherenotbetween 方法通过给定范围过滤集合:

$collection = collect([
    ['product' => 'desk', 'price' => 200],
    ['product' => 'chair', 'price' => 80],
    ['product' => 'bookcase', 'price' => 150],
    ['product' => 'pencil', 'price' => 30],
    ['product' => 'door', 'price' => 100],
]);
​
$filtered = $collection->wherenotbetween('price', [100, 200]);
​
$filtered->all();
​
/*
    [
        ['product' => 'chair', 'price' => 80],
        ['product' => 'pencil', 'price' => 30],
    ]
*/

wherenotin()

wherenotin 方法通过给定键值过滤不在给定数组中的集合数据项:

$collection = collect([
    ['product' => 'desk', 'price' => 200],
    ['product' => 'chair', 'price' => 100],
    ['product' => 'bookcase', 'price' => 150],
    ['product' => 'door', 'price' => 100],
]);
​
$filtered = $collection->wherenotin('price', [150, 200]);
​
$filtered->all();
​
/*
    [
        ['product' => 'chair', 'price' => 100],
        ['product' => 'door', 'price' => 100],
    ]
*/

wherenotin 方法在检查集合项值的时候使用「宽松」比较,也就是说整型字符串和整型数值被看作是相等的。要想进行严格过滤可以使用 wherenotinstrict 方法。

wherenotinstrict()

该方法和 wherenotin 方法签名一样,不同之处在于所有值都使用「严格」比较。

wherenotnull()

wherenotnull() 方法会筛选出给定键对应值不为空的项:

$collection = collect([
    ['name' => 'desk'],
    ['name' => null],
    ['name' => 'bookcase'],
]);
​
$filtered = $collection->wherenotnull('name');
​
$filtered->all();
​
/*
    [
        ['name' => 'desk'],
        ['name' => 'bookcase'],
    ]
*/

wherenull()

wherenull 方法会筛选出给定键对应值为空的项:

$collection = collect([
    ['name' => 'desk'],
    ['name' => null],
    ['name' => 'bookcase'],
]);
​
$filtered = $collection->wherenull('name');
​
$filtered->all();
​
/*
    [
        ['name' => null],
    ]
*/

wrap()

静态方法wrap会将给定值封装到集合中:

$collection = collection::wrap('john doe');
$collection->all();
// ['john doe']
$collection = collection::wrap(['john doe']);
$collection->all();
// ['john doe']
$collection = collection::wrap(collect('john doe'));
$collection->all();
// ['john doe']

zip()

zip 方法在与集合的值对应的索引处合并给定数组的值:

$collection = collect(['chair', 'desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['chair', 100], ['desk', 200]]

查看笔记

扫码一下
查看教程更方便
网站地图