---
### 1. collection 的使用
#### 1.1 获取键值对
$collect = collect([1,2,3]);
$collectArray = $collect->toArray();
$all = $collect->all();
$keyValueCollect = collect(['k1' => 'v1', 'k2' => 'v2', 'k3' => 'v3']);
$keys = $keyValueCollect->keys()->toArray();
$values = $keyValueCollect->values()->toArray();
$keyValueCollect->last();//最后一个元素
$keyValueCollect->only('k1', 'k2'); //只返回特定的值/
$product = Product::all();
$title = $product->pluck('title')->dump(); //只看这一列
$take = $product->take(2)->dump(); //只看前面两条
$product->toJson(); //转换为JSON
---
#### 1.2 聚合运算
$ret = $product->pluck('title')->implode(','); //分割集合
//聚合运算
$product = Product::all()->pluck('price'); //获取集合中某一列
$product->count(); //多少
$product->sum(); //合
$product->max(); //最大值
$product->min(); /最小值
---
### 1.3 集合中的判断查找
//判断查找
$exists = collect(['v1', 'v2', 'v3'])->contains('v2');
collect([1,2,3])->diff([2,3])->dd(); //差异比对 array_diff
$collect->has('k1'); //判断是否有某个键
collect([])->isEmpty(); //是否判空 集合不能通过 empty 来判断
//集合和数组是不一样的
$products = Product::all(); //返回一个集合
$products->where('id', 3); //集合筛选
---
### 1.4 集合中的遍历与过滤
//集合的遍历
$products->each(function ($item){
var_dump($item->id);
});
//替换产生一个新的集合
$products->map(function ($item){
return $item->id;
});
$products->keyBy('id')->toArray(); //把主键放到ID列
$products->groupBy('category_id')->toArray(); //分组
//集合过滤
$products->filter(function ($item){
return $item->id > 3;
})->dd();
$collect->flip()->toArray(); //key value 互换
$collect->reverse()->toArray(); //逆序
collect([12,3,4,43,4,2])->sortByDesc()->dd(); //降序排序
$products->sortByDesc(function ($product){
return $product->price();
});
collect(['k1', 'k2'])->combine(['v1', 'v2'])->dd(); //键值对合并成新的数组
collect(['k1', 'k2'])->crossJoin(['v1', 'v2'])->dd(); //排列组合笛卡尔积