站长图库向大家介绍了Laravel Collection等相关知识,希望对您有所帮助
下面给大家介绍Laravel Collection的实际使用场景,希望对需要的朋友有所帮助!
Laravel Collection 实际使用
这篇笔记用来整理Collection 在Laravel 的实际应用场景。
求和
需求:遍历$orders 数组,求price 的和。<?php// 引入packagerequire __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、使用传统的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:将多维数组转换为一维。
sum:返回数组的和。
3、使用集合的flatMap、pluck、sum:
$sum = collect($orders)->flatMap(function($order){ return $order['order_products'];})->pluck('price')->sum();echo $sum;flatMap:和map 类似,不过区别在于flatMap 可以直接使用返回的新集合。
4、使用集合的flatMap、sum:
$sum = collect($orders)->flatMap(function($order){ return $order['order_products'];})->sum('price');sum:可以接收一个列名作为参数进行求和。
格式化数据
需求:将如下结构的数组,格式化成下面的新数组。// 带格式化数组$gates = [ 'BaiYun_A_A17', 'BeiJing_J7', 'ShuangLiu_K203', 'HongQiao_A157', 'A2', 'BaiYun_B_B230']; // 新数组$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:将字符串进行分割成数组
last:获取最后一个元素
统计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、传统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: &

