Laravel collect妙用
Posted 李傲强
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel collect妙用相关的知识,希望对你有一定的参考价值。
需求
$arr = array(
[
‘name‘ => "shawn",
"email" => "[email protected]",
"company" => "QQ"
],
[
‘name‘ => "nicole",
"email" => "[email protected]",
"company" => "360"
],
[
‘name‘ => "test",
"email" => "[email protected]",
"company" => "baidu"
]
);
//转化成
$lookup = array(
"shawn" => "[email protected]",
"nicole" => "[email protected]",
"test" =>"[email protected]"
);
方法一:
$lookup = collect($arr)->pluck("email","name")->toarray();
方法二:
$lookup = collect($arr)->reduce(function($lookup,$item){
$lookup[$item["name"]] = $item["email"];
return $lookup;
},[]);
//reduce方法调用的是 array_reduce()方法
//array_reduce($arr,callback,initial);
以上是关于Laravel collect妙用的主要内容,如果未能解决你的问题,请参考以下文章