>  기사  >  PHP 프레임워크  >  Laravel Collection의 실제 사용 시나리오가 무엇인지 알고 계시나요?

Laravel Collection의 실제 사용 시나리오가 무엇인지 알고 계시나요?

藏色散人
藏色散人앞으로
2021-08-26 15:26:512125검색

다음 튜토리얼 칼럼인 Laravel에서는 Laravel Collection의 실제 사용 시나리오를 소개하겠습니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

이 노트는 Laravel에서 Collection의 실제 적용 시나리오를 정리하는 데 사용됩니다.

Summing

요구 사항: $orders 배열을 탐색하고 가격 합계를 찾습니다.
<?php
// 引入package
require __DIR__ . &#39;/vendor/autoload.php&#39;;

$orders = [[
    &#39;id&#39;            =>      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. 컬렉션의 맵, 병합 및 합계 사용:
$sum = collect($orders)->map(function($order){
    return $order['order_products'];
})->flatten(1)->map(function($order){
    return $order['price'];
})->sum();

echo $sum;

map: 컬렉션을 탐색하고 새 컬렉션을 반환합니다.
Flatten: 다차원 배열을 1차원으로 변환합니다.
sum: 배열의 합계를 반환합니다.

3. 컬렉션의 flatMap, pluck 및 sum을 사용하세요.
$sum = collect($orders)->flatMap(function($order){
    return $order['order_products'];
})->pluck('price')->sum();
echo $sum;

flatMap: map과 비슷하지만 차이점은 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 分,一个 IssueCommentEvent4. 컬렉션의 flatMap과 sum을 사용하세요.

$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);
sum: 합계를 위한 매개변수로 열 이름을 받을 수 있습니다.

데이터 포맷

요구 사항: 다음 구조의 배열을 아래의 새 배열로 포맷합니다.
$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;
    }
}
1. 컬렉션의 맵과
$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의 분해 및 끝을 사용합니다. 컬렉션의 맵, 분해, 마지막 및 toArray를 사용합니다.
$score = $events->pluck('type')->map(function($eventType) {
   return collect([
       'PushEvent'=> 5,
       'CreateEvent'=> 4,
       'IssueEvent'=> 3,
       'IssueCommentEvent'=> 2
   ])->get($eventType, 1); // 如果不存在则默认等于1
})->sum();
explode: 문자열을 배열로 분할합니다.

last: 마지막 An 요소 가져오기

statistics GitHub Event

먼저 이 링크를 통해 개인 이벤트 json을 가져옵니다.

한 개의 PushEvent는 5포인트, 하나의 CreateEvent는 4포인트, 하나의 IssueCommentEvent는 3포인트, 하나의 IssueCommentEvent 2점, 그 외 이벤트는 1점으로 현재 사용자의 총 시간 점수를 계산합니다. <strong><pre class="brush:php;toolbar:false">class GithubScore {     private $events;     private function __construct($events){         $this-&gt;events = $events;     }     public static function score($events) {         return (new static($events))-&gt;scoreEvents();     }     private function scoreEvents() {         return $this-&gt;events-&gt;pluck('type')-&gt;map(function($eventType){             return $this-&gt;lookupEventScore($eventType, 1);         })-&gt;sum();     }     public function lookupEventScore($eventType, $default_value) {        return collect([            'PushEvent'=&gt; 5,            'CreateEvent'=&gt; 4,            'IssueEvent'=&gt; 3,            'IssueCommentEvent'=&gt; 2        ])-&gt;get($eventType, $default_value); // 如果不存在则默认等于1     } } var_dump(GithubScore::score($events));</pre>1. 기존 foreach 방법: <pre class="brush:php;toolbar:false">$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.' ]; // 格式化之后的结果 - 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.</pre>2. 집합의 map, pluck 및 sum 메서드 사용: <pre class="brush:php;toolbar:false">$comment = '- ' . array_shift($messages); foreach ($messages as $message) {     $comment .= &quot;\n -  ${message}&quot;; } var_dump($comment);</pre></strong> 집합의 체인 프로그래밍을 사용하면 위의 여러 순회 문제를 해결할 수 있습니다.

3. 컬렉션에서 map, pluck, get 메소드를 사용하세요:
$comment = collect($messages)->map(function($message){
    return '- ' . $message;
})->implode("\n");
var_dump($comment);
4. 이 요구사항을 클래스로 캡슐화해 보세요:
$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
];
Format data

요구사항: 다음 데이터를 새로운 구조로 포맷하세요.
$profit = [];
foreach($thisYear as $key => $monthly){
    $profit[$key] = $monthly - $lastYear[$key];
}
var_dump($profit);
1. 기존 foreach 방법:
$profit = collect($thisYear)->zip($lastYear)->map(function($monthly){
    return $monthly->first() - $monthly->last();
});
2.
$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.'
    ]
];

// 格式化之后的结果
$lookup = [
    'example' => 'example@example.com',
    'Lucy' => ‘lucy@example.com’,
    'Taylor'=> 'toylor@laravel.com'
];

다중 배열을 사용하여 차이를 찾습니다.

요구 사항: 두 개의 데이터 세트가 각각 작년 수익과 올해 수익을 나타냅니다. 손익 상황. 🎜
$emails = [];
foreach ($employees as $key => $value) {
    $emails[$value['name']] = $value['email'];
}
1. 기존 foreach 방법:
$emails = collect($employees)->reduce(function($emailLookup, $employee){
    $emailLookup[$employee['name']] = $employee['email'];
    return $emailLookup;
},[]);
2. 컬렉션의 첫 번째, 마지막인 zip 사용:
$emails = collect($employees)->pluck('name', 'email');
🎜zip: 주어진 배열의 값을 해당 인덱스의 원본 컬렉션의 값과 병합합니다. 🎜🎜🎜조회 배열 만들기🎜🎜🎜요구 사항: 다음 배열을 다음 결과로 형식화합니다. 🎜rrreee1. 기존 foreach 방법: rrreee2 집합의 축소 방법을 사용합니다. rrreee🎜reduce: 각 반복의 결과를 다음 세트가 단일 값으로 줄어들 때까지 반복합니다. 🎜3. pluck 수집 방법 사용: rrreee🎜🎜🎜관련 권장 사항: 🎜최신 5개 Laravel 비디오 튜토리얼🎜🎜🎜

위 내용은 Laravel Collection의 실제 사용 시나리오가 무엇인지 알고 계시나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제