laravel collet分组

转自 : https://my.oschina.net/ives/blog/825988

collect提供了大量对数组的处理方法,使处理数组更加方便,以下函数在项目中可以考虑借鉴

一、sum() 用于求和

sum()    
示例1.:collect([1,2,3])->sum();//6
示例2.:$list = [
            ['name'=>'支付宝','money'=>'10'],
            ['name'=>'微信','money'=>'10.3'],
        ];
        collect($list)->sum('money');//20.3

二、unique()

unique方法返回集合中所有的唯一数据项:

$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
返回的集合保持原来的数组键,在本例中我们使用values方法重置这些键为连续的数字索引。

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

$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'],
    ]
*/
原文地址:https://www.cnblogs.com/phpk/p/14139963.html