站長資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        你知道Laravel Collection的實際使用場景有哪些嗎?

        下面由Laravel教程欄目給大家介紹Laravel Collection的實際使用場景,希望對需要的朋友有所幫助!

        這篇筆記用來整理Collection 在Laravel 的實際應用場景。

        求和

        需求:遍歷$orders 數(shù)組,求price 的和。

        <?php // 引入package require __DIR__ . '/vendor/autoload.php';  $orders = [[     'id'            =>      1,     'user_id'       =>      1,     'number'        =>      '13908080808',     'status'        =>      0,     'fee'           =>      10,     'discount'      =>      44,     'order_products'=> [         ['order_id'=>1,'product_id'=>1,'param'=>'6寸','price'=>555.00,'product'=>['id'=>1,'name'=>'蛋糕名稱','images'=>[]]],         ['order_id'=>1,'product_id'=>1,'param'=>'7寸','price'=>333.00,'product'=>['id'=>1,'name'=>'蛋糕名稱','images'=>[]]],     ], ]];

        1.使用傳統(tǒng)的foreach 方式進行遍歷:

        $sum = 0; foreach ($orders as $order) {     foreach ($order['order_products'] as $item) {         $sum += $item['price'];     } } echo $sum;

        2.使用集合的map、flatten、sum:

        $sum = collect($orders)->map(function($order){     return $order['order_products']; })->flatten(1)->map(function($order){     return $order['price']; })->sum();  echo $sum;

        map:遍歷集合,返回一個新的集合。
        flatten:將多維數(shù)組轉(zhuǎn)換為一維。
        sum:返回數(shù)組的和。

        3.使用集合的flatMap、pluck、sum:

        $sum = collect($orders)->flatMap(function($order){     return $order['order_products']; })->pluck('price')->sum(); echo $sum;

        flatMap:和map 類似,不過區(qū)別在于flatMap 可以直接使用返回的新集合。

        4.使用集合的flatMap、sum:

        $sum = collect($orders)->flatMap(function($order){     return $order['order_products']; })->sum('price');

        sum:可以接收一個列名作為參數(shù)進行求和。

        格式化數(shù)據(jù)

        需求:將如下結(jié)構(gòu)的數(shù)組,格式化成下面的新數(shù)組。

        // 帶格式化數(shù)組 $gates = [     'BaiYun_A_A17',     'BeiJing_J7',     'ShuangLiu_K203',     'HongQiao_A157',     'A2',     'BaiYun_B_B230' ];  // 新數(shù)組 $boards = [     'A17',     'J7',     'K203',     'A157',     'A2',     'B230' ];

        1.使用foreach 進行遍歷:

        $res = []; foreach($gates as $key => $gate) {     if(strpos($gate, '_') === false) {         $res[$key] = $gate;     }else{         $offset = strrpos($gate, '_') + 1;         $res[$key] = mb_substr($gate , $offset);     } } var_dump($res);

        2.使用集合的map以及php 的explode、end:

        $res = collect($gates)->map(function($gate) {     $parts = explode('_', $gate);     return end($parts); });

        3.使用集合的map、explode、last、toArray:

        $res = collect($gates)->map(function($gate) {     return collect(explode('_', $gate))->last(); })->toArray();

        explode:將字符串進行分割成數(shù)組
        last:獲取最后一個元素

        統(tǒng)計GitHub Event

        首先,通過此鏈接獲取到個人事件json。

        一個 PushEvent計 5 分,一個 CreateEvent 計 4 分,一個 IssueCommentEvent計 3 分,一個 IssueCommentEvent 計 2 分,除此之外的其它類型的事件計 1 分,計算當前用戶的時間得分總和。

        $opts = [         'http' => [                 'method' => 'GET',                 'header' => [                         'User-Agent: PHP'                 ]         ] ]; $context = stream_context_create($opts); $events = json_decode(file_get_contents('http://api.github.com/users/0xAiKang/events', false, $context), true);

        1.傳統(tǒng)foreach 方式:

        $eventTypes = []; // 事件類型 $score = 0; // 總得分 foreach ($events as $event) {     $eventTypes[] = $event['type']; }  foreach($eventTypes as $eventType) {     switch ($eventType) {         case 'PushEvent':         $score += 5;         break;         case 'CreateEvent':         $score += 4;         break;         case 'IssueEvent':         $score += 3;         break;         case 'IssueCommentEvent':         $score += 2;         break;         default:         $score += 1;         break;     } }

        2.使用集合的map、pluck、sum 方法:

        $score = $events->pluck('type')->map(function($eventType) {    switch ($eventType) {       case 'PushEvent':       return 5;       case 'CreateEvent':       return 4;       case 'IssueEvent':       return 3;       case 'IssueCommentEvent':       return 2;       default:       return 1;   } })->sum();

        使用集合的鏈式編程,可以很好地解決上面那種多次遍歷的問題。

        3.使用集合中的map、pluck、get 方法:

        $score = $events->pluck('type')->map(function($eventType) {    return collect([        'PushEvent'=> 5,        'CreateEvent'=> 4,        'IssueEvent'=> 3,        'IssueCommentEvent'=> 2    ])->get($eventType, 1); // 如果不存在則默認等于1 })->sum();

        4.嘗試將該需求,封裝成一個類:

        class GithubScore {     private $events;      private function __construct($events){         $this->events = $events;     }      public static function score($events) {         return (new static($events))->scoreEvents();     }      private function scoreEvents() {         return $this->events->pluck('type')->map(function($eventType){             return $this->lookupEventScore($eventType, 1);         })->sum();     }      public function lookupEventScore($eventType, $default_value) {        return collect([            'PushEvent'=> 5,            'CreateEvent'=> 4,            'IssueEvent'=> 3,            'IssueCommentEvent'=> 2        ])->get($eventType, $default_value); // 如果不存在則默認等于1     } }  var_dump(GithubScore::score($events));

        格式化數(shù)據(jù)

        需求:將以下數(shù)據(jù)格式化成新的結(jié)構(gòu)。

        $messages = [     'Should be working now for all Providers.',     'If you see one where spaces are in the title let me know.',     'But there should not have blank in the key of config or .env file.' ];  // 格式化之后的結(jié)果 - Should be working now for all Providers. n - If you see one where spaces are in the title let me know. n - But there should not have blank in the key of config or .env file.

        1.傳統(tǒng)的foreach 方式:

        $comment = '- ' . array_shift($messages); foreach ($messages as $message) {     $comment .= "n -  ${message}"; } var_dump($comment);

        2.使用集合的map、implode方法:

        $comment = collect($messages)->map(function($message){     return '- ' . $message; })->implode("n"); var_dump($comment);

        多個數(shù)組求差

        需求:兩組數(shù)據(jù)分別代表去年的營收和今年的營收,求每個月的盈虧情況。

        $lastYear = [     6345.75,     9839.45,     7134.60,     9479.50,     9928.0,     8652.00,     7658.40,     10245.40,     7889.40,     3892.40,     3638.40,     2339.40 ];  $thisYear = [     6145.75,     6895.00,     3434.00,     9349350,     9478.60,     7652.80,     4758.40,     10945.40,     3689.40,     8992.40,     7588.40,     2239.40 ];

        1.傳統(tǒng)的foreach 方式:

        $profit = []; foreach($thisYear as $key => $monthly){     $profit[$key] = $monthly - $lastYear[$key]; } var_dump($profit);

        2.使用集合的zip、first、last:

        $profit = collect($thisYear)->zip($lastYear)->map(function($monthly){     return $monthly->first() - $monthly->last(); });

        zip:將給定數(shù)組的值與相應索引處的原集合的值合并在一起。

        創(chuàng)建lookup 數(shù)組

        需求:將如下數(shù)組格式化成下面的結(jié)果:

        $employees = [     [         'name' => 'example',         'email' => 'example@exmaple.com',         'company' => 'example Inc.'     ],     [         'name' => 'Lucy',         'email' => 'lucy@example.com',         'company' => 'ibm Inc.'     ],     [         'name' => 'Taylor',         'email' => 'toylor@laravel.com',         'company'=>'Laravel Inc.'     ] ];  // 格式化之后的結(jié)果 $lookup = [     'example' => 'example@example.com',     'Lucy' => ‘lucy@example.com’,     'Taylor'=> 'toylor@laravel.com' ];

        1.傳統(tǒng)的foreach 方式:

        $emails = []; foreach ($employees as $key => $value) {     $emails[$value['name']] = $value['email']; }

        2.使用集合的reduce 方法:

        $emails = collect($employees)->reduce(function($emailLookup, $employee){     $emailLookup[$employee['name']] = $employee['email'];     return $emailLookup; },[]);

        reduce:將每次迭代的結(jié)果傳遞給下一次迭代直到集合減少為單個值。

        3.使用集合的pluck 方法:

        $emails = collect($employees)->pluck('name', 'email');

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
        主站蜘蛛池模板: 国内精品久久久久影院日本| 中文字幕精品视频| 国产a视频精品免费观看| 麻豆精品三级全部视频| 色偷偷888欧美精品久久久| 亚洲AV无码精品色午夜果冻不卡| 欧美一区二区精品| 精品无码一区在线观看| 婷婷久久精品国产| 国产女人18毛片水真多18精品| 2020国产精品| 无码人妻精品一区二区三区夜夜嗨 | 精品人妻无码专区中文字幕| 91麻豆精品国产自产在线观看一区| 亚洲高清专区日韩精品| 久久99精品国产麻豆蜜芽| 日本久久久精品中文字幕| 精品蜜臀久久久久99网站| 亚洲精品乱码久久久久久| 老湿亚洲永久精品ww47香蕉图片| 成人亚洲日韩精品免费视频| 久久国产精品久久精品国产| 精品黑人一区二区三区| 亚洲国产精品无码专区| 亚洲精品无码久久久| 久久精品无码免费不卡| 精品人妻伦一二三区久久| 国产伦精品一区二区三区视频金莲| 91精品国产福利在线观看麻豆| 久久久国产精品网站| 伊人精品视频在线| 一色屋精品视频在线观看| 久久91精品国产91久久麻豆| 国产福利微拍精品一区二区| 99久久国产热无码精品免费 | 精品三级在线观看| 精品国产免费一区二区三区香蕉| 国产精品嫩草视频永久网址| 国产大片91精品免费观看不卡| 国产精品电影网| 欧美精品1区2区|