Laravel collect妙用

需求

     $arr = array(
         [
             'name'     => "shawn",
             "email"    => "shawn@qq.com",
             "company"  => "QQ"
         ],
         [
             'name'     => "nicole",
             "email"    => "nicole@360.com",
             "company"  => "360"
         ],
         [
             'name'     =>  "test",
             "email"    => "test@baidu.com",
             "company"  => "baidu"
         ]
     );
//转化成
     $lookup = array(
         "shawn"    =>  "shawn@qq.com",
         "nicole"   => "nicole@360.com",
         "test"     =>"test@baidu.com"
     );

方法一:

$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);
posted @ 2018-09-05 22:47  李傲强  阅读(8200)  评论(0编辑  收藏  举报