Laravel Collectionの実際の利用シーンはどのようなものかご存知ですか?

藏色散人
リリース: 2021-08-27 09:28:40
転載
2204 人が閲覧しました

以下は、#Laravel のチュートリアルコラムとして、Laravel Collection の実際の利用シーンを紹介するもので、困っている友人の参考になれば幸いです。

このノートは、Laravel における Collection の実際の適用シナリオを整理するために使用されます。

合計

要件: $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 = collect($orders)->flatMap(function($order){
    return $order['order_products'];
})->pluck('price')->sum();
echo $sum;
ログイン後にコピー
flatMap:

map と似ていますが、異なる点は、 flatMap は返された値を直接使用できることです。新しいコレクション。 4. flatMap とコレクションの合計を使用します:

$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. コレクションのマップと PHP の展開と末尾を使用します:
$res = collect($gates)->map(function($gate) {
    $parts = explode('_', $gate);
    return end($parts);
});
ログイン後にコピー
3. コレクションのマップ、展開、最後、および toArray を使用します:
$res = collect($gates)->map(function($gate) {
    return collect(explode('_', $gate))->last();
})->toArray();
ログイン後にコピー
explode: を分割します。 string into an array

last: 最後の要素を取得します

Statistics GitHub Event

まず、このリンクから個人イベントの json を取得します。

1 つの

PushEvent は 5 ポイントの価値があり、1 つの CreateEvent は 4 ポイントの価値があり、1 つの IssueCommentEvent は 3 ポイントの価値があり、1 つの 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:
        $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));
ログイン後にコピー

データのフォーマット

要件:次のデータは新しい構造にフォーマットされます。
$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.
ログイン後にコピー
1. 従来の 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);
ログイン後にコピー

差異を見つけるための複数の配列

要件: 2 つのデータ セットは最後のものを表します今年の収益と今年の収益をそれぞれ、月ごとの損益を求めます。
$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. 従来の foreach メソッド:
$profit = [];
foreach($thisYear as $key => $monthly){
    $profit[$key] = $monthly - $lastYear[$key];
}
var_dump($profit);
ログイン後にコピー
2. コレクションの最初、最後に zip を使用します:
$profit = collect($thisYear)->zip($lastYear)->map(function($monthly){
    return $monthly->first() - $monthly->last();
});
ログイン後にコピー
zip: 指定された配列の値を、対応するインデックスにある元のコレクションの値とマージします。

ルックアップ配列の作成

要件: 次の配列を次の結果にフォーマットします:
$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'
];
ログイン後にコピー
1。従来の foreach メソッド:
$emails = [];
foreach ($employees as $key => $value) {
    $emails[$value['name']] = $value['email'];
}
ログイン後にコピー
2。 set:
$emails = collect($employees)->reduce(function($emailLookup, $employee){
    $emailLookup[$employee['name']] = $employee['email'];
    return $emailLookup;
},[]);
ログイン後にコピー
reduce: セットが単一の値に減らされるまで、各反復の結果を次の反復に渡します。

3. 収集に pluck メソッドを使用する:

$emails = collect($employees)->pluck('name', 'email');
ログイン後にコピー
関連する推奨事項:

最新の 5 つの Laravel ビデオ チュートリアル

以上がLaravel Collectionの実際の利用シーンはどのようなものかご存知ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:segmentfault.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!