Laravel 框架中使用了很多优质的第三方辅助包,Collection 就是其中的优质代表,Laravel 默认使用 Collection 对数据进行封装,使用 Collection 可以极大提升编程的效率,节省开发者大量的时间和精力,消除冗余和不必要的判断语句。使程序代码更加简洁,可读性更高。[摘自coding10.com]
Collections - Sum,Max, Min,Average,Median 的使用方法
$data=collect([100,260,210,800,900]);
dump($data->min());
dump($data->max());
dump($data->average());
dump($data->sum());
dump($data->median());
$data=collect([
['price'=>100,'discount'=>0.7,'online'=>true],
['price'=>200,'discount'=>0.9,'online'=>true],
['price'=>300,'discount'=>0.9,'online'=>true],
['price'=>800,'discount'=>0.1,'online'=>true]
]);
dump($data->min('price'));
dump($data->max('price'));
dump($data->min(function ($item){
return $item['price']*$item['discount'];
}));
dump($data->min(function ($item){
if($item['online']){
return $item['price']*$item['discount'];
}
dump($data->sum(function ($item){
if($item['online']){
return $item['price']*$item['discount'];
}
Collections - 使用 filter 过滤数据 使用 dump 调式每一步的执行
$cart=collect([
['price'=>100,'discount'=>0.7,'online'=>true,'gty'=>3],
['price'=>200,'discount'=>0.9,'online'=>false,'gty'=>2],
['price'=>300,'discount'=>0.1,'online'=>false,'gty'=>8],
['price'=>600,'discount'=>0.2,'online'=>true,'gty'=>10]
]);
$result=$cart->filter(function ($item){
return $item['online'];
});
dump($result);
//filter
$result=$cart->filter(function ($item){
return $item['online'];
})->sum(function ($item){
return $item['price']*$item['discount']*$item['gty'];
});
dump($result);
});
//dump:
$result=$cart->filter(function ($item){
return $item['online'];
})->dump()->sum(function ($item){
return $item['price']*$item['discount']*$item['gty'];
});
dump($result);
//reverse:
$result=$cart->filter(function ($item){
return $item['online'];
})->dump()->reverse()->dump()->sum(function ($item){
return $item['price']*$item['discount']*$item['gty'];
});
dump($result);
Collections - 使用 each 和 eachSpread 应对各种数据质量的遍历问题
$cart=collect([
['name'=>'tom','price'=>100,'discount'=>0.7,'online'=>true,'gty'=>3],
['name'=>'jack','price'=>200,'discount'=>0.9,'online'=>false,'gty'=>2],
['name'=>'book','price'=>300,'discount'=>0.1,'online'=>false,'gty'=>8],
['name'=>'pc','price'=>600,'discount'=>0.2,'online'=>true,'gty'=>10]
]);
$result=$cart->each(function ($item){
dump($item['name']);
});
dump($result);
//退出遍历
$result=$cart->each(function ($item){
if(!$item['online']){
return false;
}
dump($item['name']);
});
//key
$result=$cart->each(function ($item,$key){
if(!$item['online']){
return false;
}
dump($item['name'].$key);
});
$cart_brief=collect([
['tom',100,0.7,true,5],
['jake',160,0.9,true,8],
['mark',300,0.4,true,30],
['green',600,0.1,false,12],
['henry',200,0.8,true,9],
]);
$result=$cart_brief->eachSpread(function ($name,$price,$discount,$online,$qty){
if(!$online){
return false;
}
dump($name.'的价格是'.$price);
});
dump($result);
Collections - 使用 map 方法按照既定规则对数据进行映射转化
$cart=collect([
['name'=>'tom','price'=>100,'discount'=>0.7,'online'=>true,'gty'=>3],
['name'=>'jack','price'=>200,'discount'=>0.9,'online'=>false,'gty'=>2],
['name'=>'book','price'=>300,'discount'=>0.1,'online'=>false,'gty'=>8],
['name'=>'pc','price'=>600,'discount'=>0.2,'online'=>true,'gty'=>10]
]);
$result=$cart->map(function ($item){
return $item['name'];
});
dump($result);
//puluck:
$result=$cart->pluck('name');
dump($result);
//random
$result=$cart->random(2)->pluck('name');
dump($result);
//only
$result=$cart->map(function ($item){
return collect($item)->only('name','price');
});
dump($result);
//except
$result=$cart->map(function ($item){
return collect($item)->except('discount','gty');
});
dump($result);
Collections - 使用 mapInto 直接将数据注入模型中调用类的方法处理数据
use App\Models\User;
...
$users=collect([
['name'=>'user1','email'=>'a@coding10.com','password'=>'12345678'],
['name'=>'user2','email'=>'b@coding10.com','password'=>'12345678'],
['name'=>'user3','email'=>'c@coding10.com','password'=>'12345678'],
['name'=>'user4','email'=>'d@coding10.com','password'=>'12345678'],
['name'=>'user5','email'=>'e@coding10.com','password'=>'12345678'],
]);
$result=$users->mapInto(User::class)->each(function ($user){
dump($user->name);
dump($user->getAuthPassword());
$user->save();
});
dump($result);
$users_brief=collect([
['user6','a6@coding10.com','12345678'],
['user7','a76@coding10.com','12345678'],
['user8','a86@coding10.com','12345678'],
['user9','a9@coding10.com','12345678'],
['user10','a10@coding10.com','12345678'],
]);
$result=$users_brief->mapSpread(function ($name,$email,$password){
return ['name'=>$name,
'email'=>$email,
'password'=>bcrypt($password)];
})->mapInto(User::class)->each(function ($user){
dump($user->name);
dump($user->getAuthPassword());
$user->save();
});
dump($result);
Collections - 使用 chunk 和 mapSpread 方法完成数据的分组和映射
$users_rough=collect([
'user16','a16@coding10.com','12345678',
'user17','a176@coding10.com','12345678',
'user18','a186@coding10.com','12345678',
'user19','a19@coding10.com','12345678',
'user11','a11@coding10.com','12345678',
]);
$result=$users_rough->chunk(3)->mapSpread(function ($name,$email,$pwd){
return [
'name'=>$name,
'email'=>$email,
'password'=>bcrypt($pwd)
];
})->mapInto(User::class)->each(function ($user){
$user->save();
});
dump($result);
Collections - 使用 mapToGroups、mapToDictionary、groupBy 对数据进行分组
$products=collect([
['name'=>'mouse','price'=>100,'online'=>true,'supplier'=>'apple'],
['name'=>'pen','price'=>200,'online'=>true,'supplier'=>'xiaomi'],
['name'=>'book','price'=>300,'online'=>false,'supplier'=>'lenovo'],
['name'=>'desk','price'=>90,'online'=>true,'supplier'=>'apple'],
['name'=>'air','price'=>300,'online'=>false,'supplier'=>'huawei'],
['name'=>'wifi','price'=>500,'online'=>true,'supplier'=>'lenovo'],
['name'=>'pad','price'=>120,'online'=>false,'supplier'=>'huawei'],
['name'=>'latiao','price'=>50,'online'=>true,'supplier'=>'xiaomi'],
]);
//mapToGroups 返回collection
$result=$products->mapToGroups(function ($data){
return [$data['supplier']=>$data];
});
dump($result);
//mapToDictionary 返回数组
$result=$products->mapToDictionary(function ($data){
return [$data['supplier']=>$data];
});
dump($result);
//groupBy 返回collection 最常用
$result=$products->groupBy(function ($data){
return $data['online'];
});
dump($result);
Collections - 使用 first、last、take、forPage 获取指定数据
$result=$products->count();
$result=$products->first();
$result=$products->last();
$result=$products->first(function ($item){
return $item['supplier']==='huawei';
});
dump($result);
$result=$products->chunk(3);
$result=$products->take(5);
dump($result);
$result=$products->forPage(2,3);
dump($result);
Collections - 使用 toArray 、toJson、all 方法实现数据格式的转化
$result=$products->toArray();//全部转为数组
$result=$products->all();//最外层转为数组
//转为Json
$result=$products->toJson();
dump($result);
Collections - 使用 where、whereIn、whereBetween 等条件查询方法筛选数据
$result=$products->where('price',100);
dump($result);
$result=$products->where('price','100');
dump($result);
//严格模式,检查数据类型
$result=$products->whereStrict('price','100');
dump($result);
//whereIn
$result=$products->whereIn('price',[100,90]);
dump($result);
$result=$products->whereNotIn('price',[100,90]);
dump($result);
$result=$products->whereBetween('price',[50,100]);
dump($result);
$result=$products->whereNotBetween('price',[50,100]);
dump($result);
//符合条件的条一条数据
$result=$products->firstwhere('price',100);
dump($result);
Collections - 使用 when、whenNotEmpty 等函数完成数据的条件查询
$result=$products->whenEmpty(function (){
dump('这是个空集合');
});
$result=$products->whenNotEmpty(function ($products){
$products->when(request('supplier'),function ($products){
dump($products->where('supplier',request('supplier')));
});
});
Collections - 使用 sortBy 解决质量极差的数据排序问题
$products=collect([
['name'=>'mouse','price'=>100,'online'=>true,'supplier'=>'apple','type'=>'T100'],
['name'=>'pen','price'=>200,'online'=>true,'supplier'=>'xiaomi','type'=>'t200'],
['name'=>'book','price'=>300,'online'=>false,'supplier'=>'lenovo','type'=>'T 300'],
['name'=>'desk','price'=>90,'online'=>true,'supplier'=>'apple','type'=>'T-100'],
['name'=>'air','price'=>300,'online'=>false,'supplier'=>'huawei','type'=>'T__20'],
['name'=>'wifi','price'=>100,'online'=>true,'supplier'=>'lenovo','type'=>'A123'],
['name'=>'pad','price'=>120,'online'=>false,'supplier'=>'huawei','type'=>'b321'],
['name'=>'latiao','price'=>50,'online'=>true,'supplier'=>'xiaomi','type'=>'b-321'],
]);
// 简单排序,以第一个参数升序
$result=$products->sort();
dump($result);
//sortBy
$result=$products->sortBy(function ($item){
return $item['price'];
});
dump($result);
//降序
$result=$products->sortByDesc(function ($item){
return $item['price'];
});
dump($result);
//复杂数据排序,实际并没有修改集合本身的值,只是指定了规则:
$result=$products->sortBy(function ($item){
return ucfirst(str_replace([' ','-','_'],'',$item['type']));
});
dump($result);
Collections - 使用 has 和 contains 方法 判断某键某值是否存在