今天发现的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);

感觉这个功能太棒了,特此转载过来!!感谢

文章原文参考:https://www.cnblogs.com/qaing123/p/9595410.html

猜你喜欢

转载自blog.csdn.net/weixin_38996069/article/details/88815186