Laravel - Digging Deeper - Collections

前言

學習一個框架, Ray 的想法是, 在深入理解底層實作的原理之前, 應該先知道這個框架的 使用方法; 先學習怎麼使用這個前人造的輪子, 再學習怎麼樣一個輪子。
所以本篇文章重點在於細讀官方文件, 並將內容理解後以 Q&A 的方式記錄下來, 加速學習以及查詢。



Introduction

Laravel Collections 中, 以下的 Example 的意思是?
  • Example
    <?php
    $collection = collect(['taylor', 'abigail', null])->map(function ($name) {
    return strtoupper($name);
    })
    ->reject(function ($name) {
    return empty($name);
    });
  • Answer
    <?php
    // 取得 collection instance 並將每個 entry 變成大寫
    $collection = collect(['taylor', 'abigail', null])->map(function ($name) {
    return strtoupper($name);
    })
    // 移除 empty entry
    ->reject(function ($name) {
    return empty($name);
    });

Extending Collections

Laravel Collections 中, 如果我要自定義一個 collection method, 在以下的 example 中, 該使用哪個 method?
  • Example
    <?php
    use Illuminate\Support\Collection;
    use Illuminate\Support\Str;

    Collection::這裡是?('toUpper', function () {
    return $this->map(function ($value) {
    return Str::upper($value);
    });
    });

    $collection = collect(['first', 'second']);

    $upper = $collection->toUpper();

    // ['FIRST', 'SECOND']
  • Answer
    <?php
    use Illuminate\Support\Collection;
    use Illuminate\Support\Str;

    Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
    return Str::upper($value);
    });
    });

    $collection = collect(['first', 'second']);

    $upper = $collection->toUpper();

    // ['FIRST', 'SECOND']


Available Methods

Laravel Collections 中, 以下的 collection method 的輸出是?
  • Example
    <?php
    collect([1, 2, 3])->all();
  • Answer
    // [1, 2, 3]
Laravel Collections 中, 以下的 collection example 中, $average 的值是?
  • Example
    <?php
    $average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
  • Answer
    20
Laravel Collections 中, 以下的 collection example 中, $average 的值是?
  • Example
    <?php
    $average = collect([1, 1, 2, 4])->avg();
  • Answer
    2
Laravel Collections 中, 以下的 collection example 中, $chunks 的值是?
  • Example
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7]);

    $chunks = $collection->chunk(4);

    $chunks->toArray();

  • Answer
    <?php
    // [[1, 2, 3, 4], [5, 6, 7]]
Laravel Collections 中, 以下的 collection example 中, $collapsed 的值是?
  • Example
    <?php
    $collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

    $collapsed = $collection->collapse();

    $collapsed->all();
  • Answer
    <?php
    // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Laravel Collections 中, 以下的 collection example 中, $combined 的值是?
  • Example
    <?php
    $collection = collect(['name', 'age']);

    $combined = $collection->combine(['George', 29]);

    $combined->all();
  • Answer
    <?php
    // ['name' => 'George', 'age' => 29]
Laravel Collections 中, 以下的 collection example 中, $collectionB 的值是?
  • Example
    <?php
    $collectionA = collect([1, 2, 3]);

    $collectionB = $collectionA->collect();

    $collectionB->all();

  • Answer
    <?php
    // [1, 2, 3]
以下的 Laravel example code 的意思是?
  • Example
    <?php
    $lazyCollection = LazyCollection::make(function () {
    yield 1;
    yield 2;
    yield 3;
    });

    $collection = $lazyCollection->collect();

    get_class($collection);

    // 'Illuminate\Support\Collection'

    $collection->all();

    // [1, 2, 3]
  • Answer
    將 lazyCollection 轉成一般的 collection
Laravel Collections 中, 以下的 collection example 中, $concatenated 的值是?
  • Example
    <?php
    $collection = collect(['John Doe']);

    $concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);

    $concatenated->all();

  • Answer
    <?php
    // ['John Doe', 'Jane Doe', 'Johnny Doe']
Laravel Collections 中, 以下的 example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'Desk', 'price' => 100]);

    $collection->contains('Desk');
  • Answer:
    true
Laravel Collections 中, 以下的 example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'Desk', 'price' => 100]);
    $collection->contains('New York');
  • Answer:
    false
Laravel Collections 中, 以下的 example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ]);

    $collection->contains('product', 'Bookcase');
  • Answer:
    false
以下的 Laravel Collections example 中, 邏輯是?
  • Example:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ]);

    $collection->contains('product', 'Bookcase');

    // false
  • Answer:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ]);

    // 驗該 collection 中有無 'product' => 'Bookcase' 的 key / value
    $collection->contains('product', 'Bookcase');

    // false
以下的 Laravel Collections example 中, 如果我要 判斷該 collection 中是否有大於 3 的 value, 該在 contains method 中帶入什麼參數?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $collection->contains(這裡是?);

    // true
  • Answer:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $collection->contains(function ($value, $key) {
    return $value > 3;
    });

    // true
Laravel collection method contains() 是使用 loose comparison 還是 strict comparison?

loose comparison

Laravel collection method contains()containsStrict() 差別是?
  • contains(): loose comparison
  • containsStrict(): strict comparison
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $collection->count();
  • Answer:
    4
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 2, 2, 3]);

    $counted = $collection->countBy();

    $counted->all();
  • Answer:

[1 => 1, 2 => 3, 3 => 1]

以下的 Laravel Collections example 中, 邏輯是?
  • Example:
    <?php
    $collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);

    $counted = $collection->countBy(function ($email) {
    return substr(strrchr($email, "@"), 1);
    });

    $counted->all();

    // ['gmail.com' => 2, 'yahoo.com' => 1]
  • Answer:
    <?php
    $collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']);

    // strrchr 取得 "@ 最後一次出現的位置" 到 "最末" 字串, 即 @yahoo.com, @carlos@gmail.com
    // substr 取得位置 1 到最末, 即 yahoo.com, carlos@gmail
    $counted = $collection->countBy(function ($email) {
    return substr(strrchr($email, "@"), 1);
    });

    $counted->all();

    // ['gmail.com' => 2, 'yahoo.com' => 1]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2]);

    $matrix = $collection->crossJoin(['a', 'b']);

    $matrix->all();
  • Answer:
    <?php
    /*
    [
    [1, 'a'],
    [1, 'b'],
    [2, 'a'],
    [2, 'b'],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2]);

    $matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);

    $matrix->all();
  • Example:
    <?php
    /*
    [
    [1, 'a', 'I'],
    [1, 'a', 'II'],
    [1, 'b', 'I'],
    [1, 'b', 'II'],
    [2, 'a', 'I'],
    [2, 'a', 'II'],
    [2, 'b', 'I'],
    [2, 'b', 'II'],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['John Doe', 'Jane Doe']);

    $collection->dd();
  • Answer:
    <?php
    /*
    Collection {
    #items: array:2 [
    0 => "John Doe"
    1 => "Jane Doe"
    ]
    }
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $diff = $collection->diff([2, 4, 6, 8]);

    $diff->all();
  • Answer:
    <?php
    // [1, 3, 5]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6
    ]);

    $diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6,
    ]);

    $diff->all();
  • Answer:
    <?php
    // ['color' => 'orange', 'remain' => 6]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'one' => 10,
    'two' => 20,
    'three' => 30,
    'four' => 40,
    'five' => 50,
    ]);

    $diff = $collection->diffKeys([
    'two' => 2,
    'four' => 4,
    'six' => 6,
    'eight' => 8,
    ]);

    $diff->all();
  • Answer:
    <?php
    // ['one' => 10, 'three' => 30, 'five' => 50]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['John Doe', 'Jane Doe']);

    $collection->dump();
  • Answer:
    <?php
    /*
    Collection {
    #items: array:2 [
    0 => "John Doe"
    1 => "Jane Doe"
    ]
    }
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['a', 'b', 'a', 'c', 'b']);

    $collection->duplicates();
  • Answer:
    <?php
    // [2 => 'a', 4 => 'b']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $employees = collect([
    ['email' => 'abigail@example.com', 'position' => 'Developer'],
    ['email' => 'james@example.com', 'position' => 'Designer'],
    ['email' => 'victoria@example.com', 'position' => 'Developer'],
    ])

    $employees->duplicates('position');
  • Answer:
    <?php
    // [2 => 'Developer']
以下的 Laravel Collections method duplicatesduplicatesStrict 差別在於??

loose comparison 與 strict comparison

以下的 Laravel Collections method 中, foeach 相當於哪個 collection method??

collection.each

以下的 Laravel Collections method each 中, 在以下的 example, 如果我要打斷 iteration, 該怎麼做?
  • Example:
    <?php
    $collection->each(function ($item, $key) {
    if (/* some condition */) {
    // 這裡要 return?
    }
    });
  • Answer:
    <?php
    $collection->each(function ($item, $key) {
    if (/* some condition */) {
    return false;
    }
    });
以下的 Laravel example code 的意思是?
  • Example:
    <?php
    $collection = collect([['John Doe', 35], ['Jane Doe', 33]]);

    $collection->eachSpread(function ($name, $age) {
    //
    });
  • Answer:
    使用 eachSpread iterate 每一個 nested item, 如果裡頭的動作是 echo $name, 輸出為 John Doe, Jane Doe
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([1, 2, 3, 4])->every(function ($value, $key) {
    return $value > 2;
    });
  • Answer:
    <?php
    // false
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([]);

    $collection->every(function ($value, $key) {
    return $value > 2;
    });
  • Answer:
    // true
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);

    $filtered = $collection->except(['price', 'discount']);

    $filtered->all();
  • Answer:
    <?php
    // ['product_id' => 1]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
    });

    $filtered->all();
  • Answer:
    <?php
    // [3, 4]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, null, false, '', 0, []]);

    $collection->filter()->all();
  • Answer:
    <?php
    // [1, 2, 3]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([1, 2, 3, 4])->first(function ($value, $key) {
    return $value > 2;
    });
  • Answer:
    <?php
    // 3
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([1, 2, 3, 4])->first();
  • Answer:
    <?php
    // 1
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
    ]);

    $collection->firstWhere('name', 'Linda');
  • Answer:
    <?php
    // ['name' => 'Linda', 'age' => 14]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
    ]);

    $collection->firstWhere('age', '>=', 18);
  • Answer:
    <?php
    // ['name' => 'Diego', 'age' => 23]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Regena', 'age' => null],
    ['name' => 'Linda', 'age' => 14],
    ['name' => 'Diego', 'age' => 23],
    ['name' => 'Linda', 'age' => 84],
    ]);

    $collection->firstWhere('age');
  • Answer:
    <?php
    // ['name' => 'Linda', 'age' => 14]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Sally'],
    ['school' => 'Arkansas'],
    ['age' => 28]
    ]);

    $flattened = $collection->flatMap(function ($values) {
    return array_map('strtoupper', $values);
    });

    $flattened->all();
  • Answer:
    <?php
    // ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);

    $flattened = $collection->flatten();

    $flattened->all();
  • Answer:
    <?php
    // ['taylor', 'php', 'javascript'];
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'Apple' => [
    ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    ],
    'Samsung' => [
    ['name' => 'Galaxy S7', 'brand' => 'Samsung']
    ],
    ]);

    $products = $collection->flatten(1);

    $products->values()->all();
  • Answer:
    <?php
    /*
    [
    ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'Apple' => [
    ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    ],
    'Samsung' => [
    ['name' => 'Galaxy S7', 'brand' => 'Samsung']
    ],
    ]);

    $products = $collection->flatten();

    $products->values()->all();
  • Answer:
    <?php
    // ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

    $flipped = $collection->flip();

    $flipped->all();
  • Answer:
    <?php
    // ['taylor' => 'name', 'laravel' => 'framework']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

    $collection->forget('name');

    $collection->all();
  • Answer:
    <?php
    // ['framework' => 'laravel']
Laravel collection method rejectforget 差別是?

reject 會 return 一個新的 collection, forget 修改原本的 collection

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

    $chunk = $collection->forPage(2, 3);

    $chunk->all();
  • Answer:
    <?php
    // [4, 5, 6]
以下的 Laravel Collections example 中, forPage method 的 argument 代表的意思是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

    $chunk = $collection->forPage(2, 3);

    $chunk->all();

    // [4, 5, 6]
  • Answer:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

    // 2 代表第二頁的內容, 3 代表每頁顯示 3 筆資料
    $chunk = $collection->forPage(2, 3);

    $chunk->all();

    // [4, 5, 6]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

    $value = $collection->get('name');
  • Answer:
    <?php
    // taylor
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

    $value = $collection->get('hello');
  • Answer:
    <?php
    // null
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

    $value = $collection->get('foo', 'default-value');
  • Answer:
    <?php
    // default-value
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

    $collection->get('email', function () {
    return 'default-value';
    });
  • Answer:
    <?php
    // default-value
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['email' => 'ray@gmail.com', 'name' => 'taylor', 'framework' => 'laravel']);

    $collection->get('email', function () {
    return 'default-value';
    });
  • Answer:
    <?php
    // ['email' => 'ray@gmail.com']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
    ]);

    $grouped = $collection->groupBy('account_id');

    $grouped->toArray();

  • Answer:
    <?php
    /*
    [
    'account-x10' => [
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ],
    'account-x11' => [
    ['account_id' => 'account-x11', 'product' => 'Desk'],
    ],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
    ]);

    $grouped = $collection->groupBy(function ($item, $key) {
    return substr($item['account_id'], -3);
    });

    $grouped->toArray();

  • Answer:
    <?php
    /*
    [
    'x10' => [
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ],
    'x11' => [
    ['account_id' => 'account-x11', 'product' => 'Desk'],
    ],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $data = new Collection([
    10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
    20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
    30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
    40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
    ]);

    $result = $data->groupBy([
    'skill',
    function ($item) {
    return $item['roles'];
    },
    ], $preserveKeys = true);

  • Answer:
    <?php

    /*
    [
    1 => [
    'Role_1' => [
    10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
    20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
    ],
    'Role_2' => [
    20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
    ],
    'Role_3' => [
    10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
    ],
    ],
    2 => [
    'Role_1' => [
    30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
    ],
    'Role_2' => [
    40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
    ],
    ],
    ];
    */
Laravel collection method containshas 的差異是?
  • contains() 帶入一組 array 的 key/value, 或單組 key
  • has() 帶入多個 key, 以 array 的形式
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);

    $collection->has('product');
    // 輸出是?

    $collection->has(['product', 'amount']);
    // 輸出是?

    $collection->has(['amount', 'price']);
    // 輸出是?

  • Answer:
    <?php
    // true
    // true
    // false
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['account_id' => 1, 'product' => 'Desk'],
    ['account_id' => 2, 'product' => 'Chair'],
    ]);

    $collection->implode('product', ', ');
  • Answer:
    <?php
    // Desk, Chair
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([1, 2, 3, 4, 5])->implode('-');
  • Answer:
    <?php
    // '1-2-3-4-5'
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['Desk', 'Sofa', 'Chair']);

    $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);

    $intersect->all();
  • Answer:
    <?php
    // [0 => 'Desk', 2 => 'Chair']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'serial' => 'UX301', 'type' => 'screen', 'year' => 2009
    ]);

    $intersect = $collection->intersectByKeys([
    'reference' => 'UX404', 'type' => 'tab', 'year' => 2011
    ]);

    $intersect->all();
  • Answer:
    <?php
    // ['type' => 'screen', 'year' => 2009]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([])->isEmpty();
  • Answer:
    <?php
    // true
以下的 Laravel example code 的意思是?
  • Example:
    <?php
    collect([])->isNotEmpty();
  • Answer:
    false
    判斷該 collection 是否為 empty
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect(['a', 'b', 'c'])->join(', ');
  • Answer:
    <?php
    // 'a, b, c'
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect(['a', 'b', 'c'])->join(', ', ', and ');
  • Answer:
    <?php
    // 'a, b, and c'
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect(['a', 'b'])->join(', ', ' and ');
  • Answer:
    <?php
    // 'a and b'
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect(['a'])->join(', ', ' and ');
  • Answer:
    <?php
    // 'a'
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([])->join(', ', ' and ');
  • Answer:
    <?php
    // ''
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]);

    $keyed = $collection->keyBy('product_id');

    $keyed->all();
  • Answer:
    <?php
    /*
    [
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-100', 'name' => 'Chair'],
    ]);

    $keyed = $collection->keyBy('product_id');

    $keyed->all();
  • Answer:
    <?php
    /*
    [
    'prod-100' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]);

    $keyed = $collection->keyBy(function ($item) {
    return strtoupper($item['product_id']);
    });

    $keyed->all();
  • Answer:
    <?php
    /*
    [
    'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]);

    $keys = $collection->keys();

    $keys->all();
  • Answer:
    <?php
    // ['prod-100', 'prod-200']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([1, 2, 3, 4])->last(function ($value, $key) {
    return $value < 3;
    });
  • Answer:
    <?php
    // 2
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([1, 2, 3, 4])->last();
  • Answer:
    <?php
    // 4
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
    });

    $multiplied->all();
  • Answer:
    <?php
    // [2, 4, 6, 8, 10]
*Laravel collection method map()transform(), 差別在於?*

map 產生新的 collection, transform 修改現有的 collection

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    class Currency
    {
    function __construct(string $code)
    {
    $this->code = $code;
    }
    }

    $collection = collect(['USD', 'EUR', 'GBP']);

    $currencies = $collection->mapInto(Currency::class);

    $currencies->all();
  • Answer:
    <?php
    // [Currency('USD'), Currency('EUR'), Currency('GBP')]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

    $chunks = $collection->chunk(2);

    $sequence = $chunks->mapSpread(function ($even, $odd) {
    return $even + $odd;
    });

    $sequence->all();
  • Answer:
    <?php
    // [1, 5, 9, 13, 17]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    [
    'name' => 'John Doe',
    'department' => 'Sales',
    ],
    [
    'name' => 'Jane Doe',
    'department' => 'Sales',
    ],
    [
    'name' => 'Johnny Doe',
    'department' => 'Marketing',
    ]
    ]);

    $grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
    });

    $grouped->toArray();

  • Answer:
    <?php
    /*
    [
    'Sales' => ['John Doe', 'Jane Doe'],
    'Marketing' => ['Johnny Doe'],
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    [
    'name' => 'John Doe',
    'department' => 'Sales',
    ],
    [
    'name' => 'Jane Doe',
    'department' => 'Sales',
    ],
    [
    'name' => 'Johnny Doe',
    'department' => 'Marketing',
    ]
    ]);

    $grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['department'] => $item['name']];
    });
    $grouped->get('Sales')->all();
  • Answer:
    <?php
    // ['John Doe', 'Jane Doe']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    [
    'name' => 'John',
    'department' => 'Sales',
    'email' => 'john@example.com'
    ],
    [
    'name' => 'Jane',
    'department' => 'Marketing',
    'email' => 'jane@example.com'
    ]
    ]);

    $keyed = $collection->mapWithKeys(function ($item) {
    return [$item['email'] => $item['name']];
    });

    $keyed->all();
  • Answer:
    <?php
    /*
    [
    'john@example.com' => 'John',
    'jane@example.com' => 'Jane',
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
    // $max 輸出是?

    $max = collect([1, 2, 3, 4, 5])->max();
    // $max 輸出是?
  • Answer:
    <?php
    // 20

    // 5
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
    // $median 輸出是?

    $median = collect([1, 1, 2, 4])->median();
    // $median 輸出是?
  • Answer:
    <?php
    // 15

    // 1.5
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['product_id' => 1, 'price' => 100]);

    $merged = $collection->merge(['price' => 200, 'discount' => false]);

    $merged->all();
  • Answer:
    <?php
    // ['product_id' => 1, 'price' => 200, 'discount' => false]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['Desk', 'Chair']);

    $merged = $collection->merge(['Bookcase', 'Door']);

    $merged->all();
  • Answer:
    <?php
    // ['Desk', 'Chair', 'Bookcase', 'Door']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['product_id' => 1, 'price' => 100]);

    $merged = $collection->mergeRecursive(['product_id' => 2, 'price' => 200, 'discount' => false]);

    $merged->all();
  • Answer:
    <?php
    // ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
    // $min 輸出是?

    $min = collect([1, 2, 3, 4, 5])->min();
    // $min 輸出是?
  • Answer:
    <?php
    // 10

    // 1
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
    // $mode 輸出是?

    $mode = collect([1, 1, 2, 4])->mode();
    // $mode 輸出是?
  • Answer:
    <?php
    // [10]

    // [1]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

    $collection->nth(4);
  • Answer:
    <?php
    // ['a', 'e']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);

    $collection->nth(4, 1);
  • Answer:
    <?php
    // ['b', 'f']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

    $filtered = $collection->only(['product_id', 'name']);

    $filtered->all();
  • Answer:
    <?php
    // ['product_id' => 1, 'name' => 'Desk']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['A', 'B', 'C']);

    $filtered = $collection->pad(5, 0);

    $filtered->all();

    // $filtered 輸出是?

    $filtered = $collection->pad(-5, 0);

    $filtered->all();

    // $filtered 輸出是?
  • Answer:
    <?php
    // ['A', 'B', 'C', 0, 0]

    // [0, 0, 'A', 'B', 'C']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6]);

    list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) {
    return $i < 3;
    });

    $underThree->all();
    // $underThree 輸出是?

    $equalOrAboveThree->all();
    // $equalOrAboveThree 輸出是?
  • Answer:
    <?php
    // [1, 2]

    // [3, 4, 5, 6]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3]);

    $piped = $collection->pipe(function ($collection) {
    return $collection->sum();
    });
  • Answer:
    <?php
    // 6
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]);

    $plucked = $collection->pluck('name');

    $plucked->all();
  • Answer:
    <?php
    // ['Desk', 'Chair']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]);

    $plucked = $collection->pluck('name', 'product_id');

    $plucked->all();
  • Answer:
    <?php
    // ['prod-100' => 'Desk', 'prod-200' => 'Chair']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['brand' => 'Tesla', 'color' => 'red'],
    ['brand' => 'Pagani', 'color' => 'white'],
    ['brand' => 'Tesla', 'color' => 'black'],
    ['brand' => 'Pagani', 'color' => 'orange'],
    ]);

    $plucked = $collection->pluck('color', 'brand');

    $plucked->all();
  • Answer:
    <?php
    // ['Tesla' => 'black', 'Pagani' => 'orange']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $collection->pop();
    // 這裡的輸出是?

    $collection->all();
    // 這裡的輸出是?

  • Answer:
    <?php
    // 5

    // [1, 2, 3, 4]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $collection->prepend(0);

    $collection->all();
  • Answer:
    <?php
    // [0, 1, 2, 3, 4, 5]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['one' => 1, 'two' => 2]);

    $collection->prepend(0, 'zero');

    $collection->all();
  • Answer:
    <?php
    // ['zero' => 0, 'one' => 1, 'two' => 2]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);

    $collection->pull('name');
    // 這裡的輸出是?

    $collection->all();
    // 這裡的輸出是?
  • Answer:
    <?php
    // 'Desk'

    // ['product_id' => 'prod-100']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $collection->push(5);

    $collection->all();
  • Answer:
    <?php
    // [1, 2, 3, 4, 5]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['product_id' => 1, 'name' => 'Desk']);

    $collection->put('price', 100);

    $collection->all();
  • Answer:
    <?php
    // ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $collection->random();
  • Answer:
    <?php
    // 4 - (retrieved randomly)
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $random = $collection->random(3);

    $random->all();
  • Answer:
    <?php
    // [2, 4, 5] - (retrieved randomly)
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3]);

    $total = $collection->reduce(function ($carry, $item) {
    return $carry + $item;
    });
  • Answer:
    <?php
    // 6
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3]);

    $collection->reduce(function ($carry, $item) {
    return $carry + $item;
    }, 4);
  • Answer:
    <?php
    // 10
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $filtered = $collection->reject(function ($value, $key) {
    return $value > 2;
    });

    $filtered->all();
  • Answer:
    <?php
    // [1, 2]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['Taylor', 'Abigail', 'James']);

    $replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']);

    $replaced->all();
  • Answer:
    <?php
    // ['Taylor', 'Victoria', 'James', 'Finn']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['Taylor', 'Abigail', ['James', 'Victoria', 'Finn']]);

    $replaced = $collection->replaceRecursive(['Charlie', 2 => [1 => 'King']]);

    $replaced->all();
  • Answer:
    <?php
    // ['Charlie', 'Abigail', ['James', 'King', 'Finn']]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['a', 'b', 'c', 'd', 'e']);

    $reversed = $collection->reverse();

    $reversed->all();
  • Answer:
    <?php
    /*
    [
    4 => 'e',
    3 => 'd',
    2 => 'c',
    1 => 'b',
    0 => 'a',
    ]
    */
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([2, 4, 6, 8]);

    $collection->search(4);
  • Answer:
    <?php
    // 1
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([2, 4, 6, 8]);

    $collection->search('4', true);
  • Answer:
    <?php
    // false
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([2, 4, 6, 8]);

    $collection->search(function ($item, $key) {
    return $item > 5;
    });
  • Answer:
    <?php
    // 2
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $collection->shift();
    // 這裡輸出是?

    $collection->all();
    // 這裡輸出是?
  • Answer:
    <?php
    // 1

    // [2, 3, 4, 5]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $shuffled = $collection->shuffle();

    $shuffled->all();
  • Answer:
    <?php
    // [3, 2, 5, 1, 4] - (generated randomly)
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

    $collection = $collection->skip(4);

    $collection->all();
  • Answer:
    <?php
    // [5, 6, 7, 8, 9, 10]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $subset = $collection->skipUntil(function ($item) {
    return $item >= 3;
    });

    $subset->all();
  • Answer:
    <?php
    // [3, 4]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

    $collection = $collection->skip(4);

    $collection->all();
  • Answer:
    <?php
    // [5, 6, 7, 8, 9, 10]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $subset = $collection->skipUntil(3);

    $subset->all();
  • Answer:
    <?php
    // [3, 4]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $subset = $collection->skipWhile(function ($item) {
    return $item <= 3;
    });

    $subset->all();
  • Answer:
    <?php
    // [4]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

    $slice = $collection->slice(4);

    $slice->all();
  • Answer:
    <?php
    // [5, 6, 7, 8, 9, 10]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

    $slice = $collection->slice(4, 2);

    $slice->all();
  • Answer:
    <?php
    // [5, 6]
Laravel Collections method some() 是哪一個 method 的 alias?

contains()

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([5, 3, 1, 2, 4]);

    $sorted = $collection->sort();

    $sorted->values()->all();
  • Answer:
    <?php
    // [1, 2, 3, 4, 5]
Laravel Collections method sort() 是否會保留原本的 index?

會的

Laravel Collections method slice() 是否會保留原本的 index?

會的

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
    ]);

    $sorted = $collection->sortBy('price');

    $sorted->values()->all();
  • Answer:
    <?php

    /*
    [
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
    ['name' => 'Desk', 'price' => 200],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]);

    $sorted = $collection->sortBy(function ($product, $key) {
    return count($product['colors']);
    });

    $sorted->values()->all();
  • Answer:
    <?php

    /*
    [
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
    */

Laravel Collections method 中, sortBysortByDesc 差別在哪?

反方向

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([5, 3, 1, 2, 4]);

    $sorted = $collection->sortDesc();

    $sorted->values()->all();
  • Answer:
    <?php

    // [5, 4, 3, 2, 1]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
    ]);

    $sorted = $collection->sortKeys();

    $sorted->all();
  • Answer:
    <?php

    /*
    [
    'first' => 'John',
    'id' => 22345,
    'last' => 'Doe',
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    'id' => 22345,
    'first' => 'John',
    'last' => 'Doe',
    ]);

    $sorted = $collection->sortKeysDesc();

    $sorted->all();
  • Answer:
    <?php

    /*
    [
    'last' => 'Doe',
    'id' => 22345,
    'first' => 'John',
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $chunk = $collection->splice(2);

    $chunk->all();

    // 這裡輸出是?

    $collection->all();
    // 這裡輸出是?

  • Answer:
    <?php
    // [3, 4, 5]

    // [1, 2]
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $chunk = $collection->splice(2, 1);

    $chunk->all();
    // 這裡輸出是?

    $collection->all();
    // 這裡輸出是?
  • Answer:
    <?php

    // [3]

    // [1, 2, 4, 5]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $chunk = $collection->splice(2, 1, [10, 11]);

    $chunk->all();
    // 這裡輸出是?

    $collection->all();
    // 這裡輸出是?

  • Answer:
    <?php

    // [3]

    // [1, 2, 10, 11, 4, 5]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $groups = $collection->split(3);

    $groups->toArray();
  • Answer:
    <?php

    // [[1, 2], [3, 4], [5]]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([1, 2, 3, 4, 5])->sum();
  • Answer:
    <?php

    // 15

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
    ]);

    $collection->sum('pages');
  • Answer:
    <?php

    // 1272

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]);

    $collection->sum(function ($product) {
    return count($product['colors']);
    });
  • Answer:
    <?php

    // 6

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([0, 1, 2, 3, 4, 5]);

    $chunk = $collection->take(3);

    $chunk->all();
  • Answer:
    <?php

    // [0, 1, 2]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([0, 1, 2, 3, 4, 5]);

    $chunk = $collection->take(-2);

    $chunk->all();
  • Answer:
    <?php

    // [4, 5]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $subset = $collection->takeUntil(function ($item) {
    return $item >= 3;
    });

    $subset->all();
  • Answer:
    <?php

    // [1, 2]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $subset = $collection->takeUntil(3);

    $subset->all();
  • Answer:
    <?php
    // [1, 2]
    3 表示 value, 非 index
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4]);

    $subset = $collection->takeWhile(function ($item) {
    return $item < 3;
    });

    $subset->all();
  • Answer:
    <?php

    // [1, 2]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    collect([2, 4, 3, 1, 5])
    ->sort()
    ->tap(function ($collection) {
    Log::debug('Values after sorting', $collection->values()->toArray());
    })
    ->shift();
  • Answer:
    <?php

    // 1

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = Collection::times(10, function ($number) {
    return $number * 9;
    });

    $collection->all();
  • Answer:
    <?php

    // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $categories = Collection::times(3, function ($number) {
    return factory(Category::class)->create(['name' => "Category No. $number"]);
    });

    $categories->all();
  • Answer:
    <?php

    /*
    [
    ['id' => 1, 'name' => 'Category No. 1'],
    ['id' => 2, 'name' => 'Category No. 2'],
    ['id' => 3, 'name' => 'Category No. 3'],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'Desk', 'price' => 200]);

    $collection->toArray();
  • Answer:
    <?php

    /*
    [
    ['name' => 'Desk', 'price' => 200],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['name' => 'Desk', 'price' => 200]);

    $collection->toJson();
  • Answer:
    <?php

    // '{"name":"Desk", "price":200}'

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3, 4, 5]);

    $collection->transform(function ($item, $key) {
    return $item * 2;
    });

    $collection->all();
  • Answer:
    <?php

    // [2, 4, 6, 8, 10]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1 => ['a'], 2 => ['b']]);

    $union = $collection->union([3 => ['c'], 1 => ['b']]);

    $union->all();
  • Answer:
    <?php

    // [1 => ['a'], 2 => ['b'], 3 => ['c']]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 1, 2, 2, 3, 4, 2]);

    $unique = $collection->unique();

    $unique->values()->all();
  • Answer:
    <?php

    // [1, 2, 3, 4]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]);

    $unique = $collection->unique('brand');

    $unique->values()->all();
  • Answer:
    <?php

    /*
    [
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]);

    $unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
    });

    $unique->values()->all();
  • Example:
    <?php

    /*
    [
    ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
    ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
    ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
    ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
    ]
    */

Laravel Collections method unique 是 loose comparisons or strict comparison?

loose comparison

如果要使用 Laravel Collections method unique strict comparison 的話, 該使用哪個 method?

uniqueStrict()

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3]);

    $collection->unless(true, function ($collection) {
    return $collection->push(4);
    });

    $collection->unless(false, function ($collection) {
    return $collection->push(5);
    });

    $collection->all();
  • Answer:
    <?php

    // [1, 2, 3, 5]

Laravel Collections method 中, unlessEmpty 是哪個 method 的 alias?

whenNotEmpty()

Laravel Collections method 中, unlessNotEmpty 是哪個 method 的 alias?

whenEmpty()

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    Collection::unwrap(collect('John Doe'));
    // 這裡輸出是?

    Collection::unwrap(['John Doe']);
    // 這裡輸出是?

    Collection::unwrap('John Doe');
    // 這裡輸出是?
  • Answer:
    <?php
    // 如果 argument 是 array, 輸出 array, 否則則輸出 argument 本身

    // ['John Doe']

    // ['John Doe']

    // 'John Doe'
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    10 => ['product' => 'Desk', 'price' => 200],
    11 => ['product' => 'Desk', 'price' => 200]
    ]);

    $values = $collection->values();

    $values->all();
  • Answer:
    <?php
    // 會重置 key

    /*
    [
    0 => ['product' => 'Desk', 'price' => 200],
    1 => ['product' => 'Desk', 'price' => 200],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([1, 2, 3]);

    $collection->when(true, function ($collection) {
    return $collection->push(4);
    });

    $collection->when(false, function ($collection) {
    return $collection->push(5);
    });

    $collection->all();
  • Answer:
    <?php
    // 恰恰與 unless 相反

    // [1, 2, 3, 4]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['michael', 'tom']);

    $collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
    });

    $collection->all();

    // ['michael', 'tom']
  • Answer:
    <?php
    $collectionempty 時, 執行 closure 內的邏輯
    // ['michael', 'tom']
以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect();

    $collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
    });

    $collection->all();
  • Answer:
    <?php

    // ['adam']

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['michael', 'tom']);

    $collection->whenEmpty(function ($collection) {
    return $collection->push('adam');
    }, function ($collection) {
    return $collection->push('taylor');
    });

    $collection->all();
  • Answer:
    <?php

    // ['michael', 'tom', 'taylor']

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['michael', 'tom']);

    $collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
    });

    $collection->all();
  • Answer:
    <?php

    // ['michael', 'tom', 'adam']

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect();

    $collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
    });

    $collection->all();
  • Answer:
    <?php

    // []

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect();

    $collection->whenNotEmpty(function ($collection) {
    return $collection->push('adam');
    }, function ($collection) {
    return $collection->push('taylor');
    });

    $collection->all();
  • Answer:
    <?php

    // ['taylor']

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
    ]);

    $filtered = $collection->where('price', 100);

    $filtered->all();

  • Answer:
    <?php
    /*
    [
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Door', 'price' => 100],
    ]
    */

Laravel collection method where() 預設是 loose comparison, 如果要讓它是 strict comparison, 該使用哪個 method?

whereStrict

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
    ]);

    $filtered = $collection->whereBetween('price', [100, 200]);

    $filtered->all();
  • Answer:
    <?php

    /*
    [
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
    ]);

    $filtered = $collection->whereIn('price', [150, 200]);

    $filtered->all();
  • Answer:
    <?php

    /*
    [
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Bookcase', 'price' => 150],
    ]
    */

Laravel collection method whereIn() 預設是 loose comparison, 如果要讓它是 strict comparison, 該使用哪個 method?

whereInStrict

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    use App\User;
    use App\Post;

    $collection = collect([
    new User,
    new User,
    new Post,
    ]);

    $filtered = $collection->whereInstanceOf(User::class);

    $filtered->all();
  • Answer:
    <?php

    // [App\User, App\User]

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Pencil', 'price' => 30],
    ['product' => 'Door', 'price' => 100],
    ]);

    $filtered = $collection->whereNotBetween('price', [100, 200]);

    $filtered->all();
  • Answer:
    <?php

    /*
    [
    ['product' => 'Chair', 'price' => 80],
    ['product' => 'Pencil', 'price' => 30],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
    ]);

    $filtered = $collection->whereNotIn('price', [150, 200]);

    $filtered->all();
  • Answer:
    <?php

    /*
    [
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Door', 'price' => 100],
    ]
    */

如果我要使用 strict 模式的 whereNotInStrict, 可以使用哪個 method?

whereNotInStrict()

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
    ]);

    $filtered = $collection->whereNotNull('name');

    $filtered->all();
  • Answer:
    <?php

    /*
    [
    ['name' => 'Desk'],
    ['name' => 'Bookcase'],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect([
    ['name' => 'Desk'],
    ['name' => null],
    ['name' => 'Bookcase'],
    ]);

    $filtered = $collection->whereNull('name');

    $filtered->all();
  • Answer:
    <?php

    /*
    [
    ['name' => null],
    ]
    */

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = Collection::wrap('John Doe');

    $collection->all();
    // 這裡的輸出是?

    $collection = Collection::wrap(['John Doe']);

    $collection->all();
    // 這裡的輸出是?

    $collection = Collection::wrap(collect('John Doe'));

    $collection->all();
    // 這裡的輸出是?
  • Answer:
    <?php

    // ['John Doe']

    // ['John Doe']

    // ['John Doe']

以下的 Laravel Collections example 中, 輸出是?
  • Example:
    <?php
    $collection = collect(['Chair', 'Desk']);

    $zipped = $collection->zip([100, 200]);

    $zipped->all();
  • Answer:
    <?php

    // [['Chair', 100], ['Desk', 200]]



Higher Order Messages

Laravel Collections method 中, 什麼是 higher order message?

collection method 的縮寫



Lazy Collections

Introduction

以下的 Laravel example code 的意思是?
  • Example:
    <?php
    $users = App\User::cursor()->filter(function ($user) {
    return $user->id > 500;
    });

    foreach ($users as $user) {
    echo $user->id;
    }
  • Answer:
    cursor 為 PHP generator 的概念, 不會一次性的將所有 model 都 load 到 memory, 會一次 load 一個 model 並執行, 減低記憶體用量

Lazy Collection Methods

解釋以下 collection example
  • Example:
    <?php
    $lazyCollection = LazyCollection::times(INF)->tapEach(function ($value) {
    dump($value);
    });

    // Nothing has been dumped so far...

    $array = $lazyCollection->take(3)->all();

    // 1
    // 2
    // 3
  • Answer:
    <?php
    // 宣告一個無窮大的 collection, 但此 collection 必不會執行, 會等到被呼叫才會執行, tapEach 是 lazy collection 專屬的 method
    $lazyCollection = LazyCollection::times(INF)->tapEach(function ($value) {
    dump($value);
    });

    // Nothing has been dumped so far...

    // 這邊才會執行
    $array = $lazyCollection->take(3)->all();

    // 1
    // 2
    // 3
回答以下 lazy collection example 中的問題
  • Example:
    <?php
    $users = User::cursor()->remember();

    // 到此, 有 query 被執行嗎?

    $users->take(5)->all();

    // 到此, 有 query 被執行嗎?
    // 哪些 user 被從資料庫拉出?

    $users->take(20)->all();

    // 到此, 哪些 user 被從資料庫拉出?
  • Answer:
    <?php
    $users = User::cursor()->remember();

    // 到此, 有 query 被執行嗎? 沒有

    $users->take(5)->all();

    // 到此, 有 query 被執行嗎? 有哦
    // 哪些 user 被從資料庫拉出? 前 5 個 user

    $users->take(20)->all();

    // 到此, 哪些 user 被從資料庫拉出? 6 到 20, 前 5 個來自於 cache
Laravel - Database - Getting Started (官方文件原子化翻譯筆記) Laravel - Digging Deeper - HTTP Client (官方文件原子化翻譯筆記)

留言

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×