<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 集合 - [簡介](#introduction) - [創建集合](#creating-collections) - [可用的方法](#available-methods) - [高階消息傳遞](#higher-order-messages) <a name="introduction"></a> ## 簡介 `Illuminate\Support\Collection` 類提供了一個更具可讀性的、更便于處理數組數據的封裝。具體例子看下面的代碼。我們使用了 `collect` 函數從數組中創建新的集合實例,對其中的每個元素運行 `strtoupper` 函數之后再移除所有的空元素: $collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); }) ->reject(function ($name) { return empty($name); }); 正如你看到的,`Collection` 類允許你鏈式調用其方法,以達到在底層數組上優雅地執行 map 和 reject 操作。一般來說,集合是不可改變的,這意味著每個 `Collection` 方法都會返回一個全新的 `Collection` 實例。 <a name="creating-collections"></a> ### 創建集合 如上所述,輔助函數 `collect` 會為給定的數組返回一個新的 `Illuminate\Support\Collection` 實例。也就是說,創建一個集合就這么簡單: $collection = collect([1, 2, 3]); > {tip} 默認情況下, [Eloquent](/docs/{{version}}/eloquent) 查詢的結果返回的內容都是 `Collection` 實例。 <a name="available-methods"></a> ## 可用的方法 這個文檔接下來的內容,我們會探討 `Collection` 類每個可用的方法。記住,所有方法都可以以方法鏈的形式優雅地操縱數組。而且,幾乎所有的方法都會返回新的 `Collection` 實例,允許你在必要時保存集合的原始副本。 <style> #collection-method-list > p { column-count: 3; -moz-column-count: 3; -webkit-column-count: 3; column-gap: 2em; -moz-column-gap: 2em; -webkit-column-gap: 2em; } #collection-method-list a { display: block; } </style> <div id="collection-method-list" markdown="1"> [all](#method-all) [average](#method-average) [avg](#method-avg) [chunk](#method-chunk) [collapse](#method-collapse) [combine](#method-combine) [contains](#method-contains) [containsStrict](#method-containsstrict) [count](#method-count) [diff](#method-diff) [diffAssoc](#method-diffassoc) [diffKeys](#method-diffkeys) [each](#method-each) [every](#method-every) [except](#method-except) [filter](#method-filter) [first](#method-first) [flatMap](#method-flatmap) [flatten](#method-flatten) [flip](#method-flip) [forget](#method-forget) [forPage](#method-forpage) [get](#method-get) [groupBy](#method-groupby) [has](#method-has) [implode](#method-implode) [intersect](#method-intersect) [intersectKey](#method-intersectkey) [isEmpty](#method-isempty) [isNotEmpty](#method-isnotempty) [keyBy](#method-keyby) [keys](#method-keys) [last](#method-last) [map](#method-map) [mapWithKeys](#method-mapwithkeys) [max](#method-max) [median](#method-median) [merge](#method-merge) [min](#method-min) [mode](#method-mode) [nth](#method-nth) [only](#method-only) [partition](#method-partition) [pipe](#method-pipe) [pluck](#method-pluck) [pop](#method-pop) [prepend](#method-prepend) [pull](#method-pull) [push](#method-push) [put](#method-put) [random](#method-random) [reduce](#method-reduce) [reject](#method-reject) [reverse](#method-reverse) [search](#method-search) [shift](#method-shift) [shuffle](#method-shuffle) [slice](#method-slice) [sort](#method-sort) [sortBy](#method-sortby) [sortByDesc](#method-sortbydesc) [splice](#method-splice) [split](#method-split) [sum](#method-sum) [take](#method-take) [tap](#method-tap) [times](#method-times) [toArray](#method-toarray) [toJson](#method-tojson) [transform](#method-transform) [union](#method-union) [unique](#method-unique) [uniqueStrict](#method-uniquestrict) [values](#method-values) [when](#method-when) [where](#method-where) [whereStrict](#method-wherestrict) [whereIn](#method-wherein) [whereInStrict](#method-whereinstrict) [whereNotIn](#method-wherenotin) [whereNotInStrict](#method-wherenotinstrict) [zip](#method-zip) </div> <a name="method-listing"></a> ## 方法列表 <style> #collection-method code { font-size: 14px; } #collection-method:not(.first-collection-method) { margin-top: 50px; } </style> <a name="method-all"></a> #### `all()` {#collection-method .first-collection-method} `all` 方法返回該集合表示的底層 `數組`: collect([1, 2, 3])->all(); // [1, 2, 3] <a name="method-average"></a> #### `average()` {#collection-method} [`avg`](#method-avg) 方法的別名。 <a name="method-avg"></a> #### `avg()` {#collection-method} `avg` 方法返回給定鍵的 [平均值](https://en.wikipedia.org/wiki/Average): $average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo'); // 20 $average = collect([1, 1, 2, 4])->avg(); // 2 <a name="method-chunk"></a> #### `chunk()` {#collection-method} `chunk` 方法將集合拆成多個指定大小的小集合: $collection = collect([1, 2, 3, 4, 5, 6, 7]); $chunks = $collection->chunk(4); $chunks->toArray(); // [[1, 2, 3, 4], [5, 6, 7]] 這個方法特別適用在使用網格系統時的 [視圖](/docs/{{version}}/views),如 [Bootstrap](http://getbootstrap.com/css/#grid)。想像你有一個 [Eloquent](/docs/{{version}}/eloquent) 模型的集合要在網格中顯示: ```HTML @foreach ($products->chunk(3) as $chunk) <div class="row"> @foreach ($chunk as $product) <div class="col-xs-4">{{ $product->name }}</div> @endforeach </div> @endforeach ``` <a name="method-collapse"></a> #### `collapse()` {#collection-method} `collapse` 方法將多個數組合并成一個: $collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); $collapsed = $collection->collapse(); $collapsed->all(); // [1, 2, 3, 4, 5, 6, 7, 8, 9] <a name="method-combine"></a> #### `combine()` {#collection-method} `combine` 方法可以將一個集合的值作為「鍵」,再將另一個數組或者集合的值作為「值」合并成一個集合: $collection = collect(['name', 'age']); $combined = $collection->combine(['George', 29]); $combined->all(); // ['name' => 'George', 'age' => 29] <a name="method-contains"></a> #### `contains()` {#collection-method} `contains` 方法判斷集合是否包含給定的項目: $collection = collect(['name' => 'Desk', 'price' => 100]); $collection->contains('Desk'); // true $collection->contains('New York'); // false 你也可以用 `contains` 方法匹配一對鍵/值,即判斷給定的配對是否存在于集合中: $collection = collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ]); $collection->contains('product', 'Bookcase'); // false 最后,你也可以傳遞一個回調到 `contains` 方法來執行自己的真實測試: $collection = collect([1, 2, 3, 4, 5]); $collection->contains(function ($value, $key) { return $value > 5; }); // false `contains` 方法在檢查項目值時使用「寬松」比較,意味著具有整數值的字符串將被視為等于相同值的整數。 相反 [`containsStrict`](https://laravel.com/docs/5.5/collections#method-containsstrict) 方法則是使用「嚴格」比較進行過濾。 <a name="method-containsstrict"></a> #### `containsStrict()` {#collection-method} 此方法和 [`contains`](#method-contains) 方法類似,但是它卻是使用了「嚴格」比較來比較所有值。 <a name="method-count"></a> #### `count()` {#collection-method} `count` 方法返回該集合內的項目總數: $collection = collect([1, 2, 3, 4]); $collection->count(); // 4 <a name="method-diff"></a> #### `diff()` {#collection-method} `diff` 方法將集合與其它集合或純 PHP 數組進行值的比較,然后返回原集合中存在而給定集合中不存在的值: $collection = collect([1, 2, 3, 4, 5]); $diff = $collection->diff([2, 4, 6, 8]); $diff->all(); // [1, 3, 5] <a name="method-diffassoc"></a> #### `diffAssoc()` {#collection-method} `diffAssoc` 該方法與另外一個集合或基于它的鍵和值的 PHP 數組進行比較。這個方法會返回原集合不存在于給定集合中的鍵值對 : $collection = collect([ 'color' => 'orange', 'type' => 'fruit', 'remain' => 6 ]); $diff = $collection->diffAssoc([ 'color' => 'yellow', 'type' => 'fruit', 'remain' => 3, 'used' => 6 ]); $diff->all(); // ['color' => 'orange', 'remain' => 6] <a name="method-diffkeys"></a> #### `diffKeys()` {#collection-method} `diffKeys` 方法與另外一個集合或 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(); // ['one' => 10, 'three' => 30, 'five' => 50] <a name="method-each"></a> #### `each()` {#collection-method} `each` 迭代集合中的內容并將其傳遞到回調函數中: $collection = $collection->each(function ($item, $key) { // }); 如果你想要中斷對內容的迭代,那就從回調中返回 `false`: $collection = $collection->each(function ($item, $key) { if (/* some condition */) { return false; } }); <a name="method-every"></a> #### `every()` {#collection-method} `every` 方法可用于驗證集合中每一個元素都通過給定的真實測試: collect([1, 2, 3, 4])->every(function ($value, $key) { return $value > 2; }); // false <a name="method-except"></a> #### `except()` {#collection-method} `except` 方法返回集合中除了指定鍵以外的所有項目: $collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]); $filtered = $collection->except(['price', 'discount']); $filtered->all(); // ['product_id' => 1] 與 `except` 相反的方法,請查看 [only](#method-only)。 <a name="method-filter"></a> #### `filter()` {#collection-method} `filter` 方法使用給定的回調函數過濾集合的內容,只留下那些通過給定真實測試的內容: $collection = collect([1, 2, 3, 4]); $filtered = $collection->filter(function ($value, $key) { return $value > 2; }); $filtered->all(); // [3, 4] 如果沒有提供回調函數,集合中所有返回 `false` 的元素都會被移除: $collection = collect([1, 2, 3, null, false, '', 0, []]); $collection->filter()->all(); // [1, 2, 3] 與 `filter` 相反的方法,可以查看 [reject](#method-reject)。 <a name="method-first"></a> #### `first()` {#collection-method} `first` 方法返回集合中通過給定真實測試的第一個元素: collect([1, 2, 3, 4])->first(function ($value, $key) { return $value > 2; }); // 3 你也可以不傳入參數使用 `first` 方法以獲取集合中第一個元素。如果集合是空的,則會返回 `null`: collect([1, 2, 3, 4])->first(); // 1 <a name="method-flatmap"></a> #### `flatMap()` {#collection-method} `flatMap` 方法遍歷集合并將其中的每個值傳遞到給定的回調。可以通過回調修改每個值的內容再返回出來,從而形成一個新的被修改過內容的集合。然后你就可以用 `all()` 打印修改后的數組: $collection = collect([ ['name' => 'Sally'], ['school' => 'Arkansas'], ['age' => 28] ]); $flattened = $collection->flatMap(function ($values) { return array_map('strtoupper', $values); }); $flattened->all(); // ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28']; <a name="method-flatten"></a> #### `flatten()` {#collection-method} `flatten` 方法將多維集合轉為一維的: $collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]); $flattened = $collection->flatten(); $flattened->all(); // ['taylor', 'php', 'javascript']; 你還可以選擇性地傳入「深度」參數: $collection = collect([ 'Apple' => [ ['name' => 'iPhone 6S', 'brand' => 'Apple'], ], 'Samsung' => [ ['name' => 'Galaxy S7', 'brand' => 'Samsung'] ], ]); $products = $collection->flatten(1); $products->values()->all(); /* [ ['name' => 'iPhone 6S', 'brand' => 'Apple'], ['name' => 'Galaxy S7', 'brand' => 'Samsung'], ] */ 在這個例子里,調用 `flatten` 方法時不傳入深度參數的話也會將嵌套數組轉成一維的,然后返回 `['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']`。傳入深度參數能讓你限制設置返回數組的層數。 <a name="method-flip"></a> #### `flip()` {#collection-method} `flip` 方法將集合中的鍵和對應的數值進行互換: $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $flipped = $collection->flip(); $flipped->all(); // ['taylor' => 'name', 'laravel' => 'framework'] <a name="method-forget"></a> #### `forget()` {#collection-method} `forget` 方法通過給定的鍵來移除掉集合中對應的內容: $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $collection->forget('name'); $collection->all(); // ['framework' => 'laravel'] > {note} 與大多數集合的方法不同,`forget` 不會返回修改過后的新集合;它會直接修改原來的集合。 <a name="method-forpage"></a> #### `forPage()` {#collection-method} `forPage` 方法返回給定頁碼上顯示的項目的新集合。這個方法接受頁碼作為其第一個參數和每頁顯示的項目數作為其第二個參數。 $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]); $chunk = $collection->forPage(2, 3); $chunk->all(); // [4, 5, 6] <a name="method-get"></a> #### `get()` {#collection-method} `get` 方法返回給定鍵的項目。如果該鍵不存在,則返回 `null`: $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('name'); // taylor 你可以選擇性地傳遞默認值作為第二個參數: $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('foo', 'default-value'); // default-value 你甚至可以將回調函數當作默認值。如果指定的鍵不存在,就會返回回調的結果: $collection->get('email', function () { return 'default-value'; }); // default-value <a name="method-groupby"></a> #### `groupBy()` {#collection-method} `groupBy` 方法根據給定的鍵對集合內的項目進行分組: $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(); /* [ 'account-x10' => [ ['account_id' => 'account-x10', 'product' => 'Chair'], ['account_id' => 'account-x10', 'product' => 'Bookcase'], ], 'account-x11' => [ ['account_id' => 'account-x11', 'product' => 'Desk'], ], ] */ 除了傳入一個字符串的「鍵」,你還可以傳入一個回調。該回調應該返回你希望用來分組的鍵的值。 $grouped = $collection->groupBy(function ($item, $key) { return substr($item['account_id'], -3); }); $grouped->toArray(); /* [ 'x10' => [ ['account_id' => 'account-x10', 'product' => 'Chair'], ['account_id' => 'account-x10', 'product' => 'Bookcase'], ], 'x11' => [ ['account_id' => 'account-x11', 'product' => 'Desk'], ], ] */ <a name="method-has"></a> #### `has()` {#collection-method} `has` 方法判斷集合中是否存在給定的鍵: $collection = collect(['account_id' => 1, 'product' => 'Desk']); $collection->has('product'); // true <a name="method-implode"></a> #### `implode()` {#collection-method} `implode` 方法合并集合中的項目。其參數取決于集合中項目的類型。如果集合包含數組或對象,你應該傳入你希望連接的屬性的鍵,以及你希望放在值之間用來「拼接」的字符串:: $collection = collect([ ['account_id' => 1, 'product' => 'Desk'], ['account_id' => 2, 'product' => 'Chair'], ]); $collection->implode('product', ', '); // Desk, Chair 如果集合包含簡單的字符串或數值,只需要傳入「拼接」用的字符串作為該方法的唯一參數即可: collect([1, 2, 3, 4, 5])->implode('-'); // '1-2-3-4-5' <a name="method-intersect"></a> #### `intersect()` {#collection-method} `intersect` 方法從原集合中刪除不在給定「數組」或集合中的任何值。最終的集合會保留原集合的鍵: $collection = collect(['Desk', 'Sofa', 'Chair']); $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']); $intersect->all(); // [0 => 'Desk', 2 => 'Chair'] <a name="method-intersectkey"></a> #### `intersectKey()` {#collection-method} `intersectKey` 方法刪除原集合中不存在于給定「數組」或集合中的任何鍵。 $collection = collect([ 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009 ]); $intersect = $collection->intersectKey([ 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011 ]); $intersect->all(); // ['type' => 'screen', 'year' => 2009] <a name="method-isempty"></a> #### `isEmpty()` {#collection-method} 如果集合是空的,`isEmpty` 方法返回 `true`,否則返回 `false`: collect([])->isEmpty(); // true <a name="method-isnotempty"></a> #### `isNotEmpty()` {#collection-method} 如果集合不是空的,`isNotEmpty` 方法會返回 `true`:否則返回 `false`: collect([])->isNotEmpty(); // false <a name="method-keyby"></a> #### `keyBy()` {#collection-method} `keyBy` 方法以給定的鍵作為集合的鍵。如果多個項目具有相同的鍵,則只有最后一個項目會顯示在新集合中: $collection = collect([ ['product_id' => 'prod-100', 'name' => 'desk'], ['product_id' => 'prod-200', 'name' => 'chair'], ]); $keyed = $collection->keyBy('product_id'); $keyed->all(); /* [ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ] */ 你也可以傳入一個回調方法,回調返回的值會作為該集合的鍵: $keyed = $collection->keyBy(function ($item) { return strtoupper($item['product_id']); }); $keyed->all(); /* [ 'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ] */ <a name="method-keys"></a> #### `keys()` {#collection-method} `keys` 方法返回集合的所有鍵: $collection = collect([ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $keys = $collection->keys(); $keys->all(); // ['prod-100', 'prod-200'] <a name="method-last"></a> #### `last()` {#collection-method} `last` 方法返回集合中通過給定真實測試的最后一個元素: collect([1, 2, 3, 4])->last(function ($value, $key) { return $value < 3; }); // 2 你也可以不傳入參數調用 `last` 方法來獲取集合中最后一個元素。如果集合是空的,返回 `null`: collect([1, 2, 3, 4])->last(); // 4 <a name="method-map"></a> #### `map()` {#collection-method} `map` 方法遍歷集合并將每一個值傳入給定的回調。該回調可以任意修改項目并返回,從而形成新的被修改過項目的集合: $collection = collect([1, 2, 3, 4, 5]); $multiplied = $collection->map(function ($item, $key) { return $item * 2; }); $multiplied->all(); // [2, 4, 6, 8, 10] > {note} 像其他集合方法一樣,`map` 返回一個新的集合實例;它不會修改它所調用的集合。如果你想改變原集合,得使用 [`transform`](#method-transform) 方法。 <a name="method-mapwithkeys"></a> #### `mapWithKeys()` {#collection-method} `mapWithKeys` 方法遍歷集合并將每個值傳入給定的回調。回調應該返回包含一個鍵值對的關聯數組: $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(); /* [ 'john@example.com' => 'John', 'jane@example.com' => 'Jane', ] */ <a name="method-max"></a> #### `max()` {#collection-method} `max` 方法返回給定鍵的最大值: $max = collect([['foo' => 10], ['foo' => 20]])->max('foo'); // 20 $max = collect([1, 2, 3, 4, 5])->max(); // 5 <a name="method-median"></a> #### `median()` {#collection-method} `median` 方法返回給定鍵的 [中間值](https://en.wikipedia.org/wiki/Median) : $median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo'); // 15 $median = collect([1, 1, 2, 4])->median(); // 1.5 <a name="method-merge"></a> #### `merge()` {#collection-method} `merge` 方法將給定數組或集合合并到原集合。如果給定項目中的字符串鍵與原集合中的字符串鍵匹配,給定的項目的值將會覆蓋原集合中的值: $collection = collect(['product_id' => 1, 'price' => 100]); $merged = $collection->merge(['price' => 200, 'discount' => false]); $merged->all(); // ['product_id' => 1, 'price' => 200, 'discount' => false] 如果給定的項目的鍵是數字,這些值將被追加到集合的末尾: $collection = collect(['Desk', 'Chair']); $merged = $collection->merge(['Bookcase', 'Door']); $merged->all(); // ['Desk', 'Chair', 'Bookcase', 'Door'] <a name="method-min"></a> #### `min()` {#collection-method} `min` 方法返回給定鍵的最小值: $min = collect([['foo' => 10], ['foo' => 20]])->min('foo'); // 10 $min = collect([1, 2, 3, 4, 5])->min(); // 1 <a name="method-mode"></a> #### `mode()` {#collection-method} `mode` 方法返回給定鍵的 [眾數值](https://en.wikipedia.org/wiki/Mode_(statistics)): $mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo'); // [10] $mode = collect([1, 1, 2, 4])->mode(); // [1] <a name="method-nth"></a> #### `nth()` {#collection-method} `nth` 方法創建由每隔 n 個元素組成一個新的集合: $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e'] 你也可以選擇傳入一個偏移位置作為第二個參數 $collection->nth(4, 1); // ['b', 'f'] <a name="method-only"></a> #### `only()` {#collection-method} `only` 方法返回集合中給定鍵的所有項目: $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]); $filtered = $collection->only(['product_id', 'name']); $filtered->all(); // ['product_id' => 1, 'name' => 'Desk'] 與 `only` 相反的方法,請查看 [except](#method-only)。 <a name="method-partition"></a> #### `partition()` {#collection-method} `partition` 方法可以和PHP 中的 `list` 方法結合使用,來分開通過指定條件的元素以及那些不通過指定條件的元素: $collection = collect([1, 2, 3, 4, 5, 6]); list($underThree, $aboveThree) = $collection->partition(function ($i) { return $i < 3; }); <a name="method-pipe"></a> #### `pipe()` {#collection-method} `pipe` 方法將集合傳給給定的回調并返回結果: $collection = collect([1, 2, 3]); $piped = $collection->pipe(function ($collection) { return $collection->sum(); }); // 6 <a name="method-pluck"></a> #### `pluck()` {#collection-method} `pluck` 方法獲取集合中給定鍵對應的所有值: $collection = collect([ ['product_id' => 'prod-100', 'name' => 'Desk'], ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $plucked = $collection->pluck('name'); $plucked->all(); // ['Desk', 'Chair'] 你也可以通過傳入第二個參數來指定生成的集合的鍵: $plucked = $collection->pluck('name', 'product_id'); $plucked->all(); // ['prod-100' => 'Desk', 'prod-200' => 'Chair'] <a name="method-pop"></a> #### `pop()` {#collection-method} `pop` 方法移除并返回集合中的最后一個項目: $collection = collect([1, 2, 3, 4, 5]); $collection->pop(); // 5 $collection->all(); // [1, 2, 3, 4] <a name="method-prepend"></a> #### `prepend()` {#collection-method} `prepend` 方法將給定的值添加到集合的開頭: $collection = collect([1, 2, 3, 4, 5]); $collection->prepend(0); $collection->all(); // [0, 1, 2, 3, 4, 5] 你也可以傳遞第二個參數來設置前置項的鍵: $collection = collect(['one' => 1, 'two' => 2]); $collection->prepend(0, 'zero'); $collection->all(); // ['zero' => 0, 'one' => 1, 'two' => 2] <a name="method-pull"></a> #### `pull()` {#collection-method} `pull` 方法把給定鍵對應的值從集合中移除并返回: $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']); $collection->pull('name'); // 'Desk' $collection->all(); // ['product_id' => 'prod-100'] <a name="method-push"></a> #### `push()` {#collection-method} `push` 方法把給定值添加到集合的末尾: $collection = collect([1, 2, 3, 4]); $collection->push(5); $collection->all(); // [1, 2, 3, 4, 5] <a name="method-put"></a> #### `put()` {#collection-method} `put` 方法在集合內設置給定的鍵值對: $collection = collect(['product_id' => 1, 'name' => 'Desk']); $collection->put('price', 100); $collection->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100] <a name="method-random"></a> #### `random()` {#collection-method} `random` 方法從集合中返回一個隨機項: $collection = collect([1, 2, 3, 4, 5]); $collection->random(); // 4 - (retrieved randomly) 你可以選擇性傳入一個整數到 `random` 來指定要獲取的隨機項的數量。只要你顯式傳遞你希望接收的數量時,則會返回項目的集合: $random = $collection->random(3); $random->all(); // [0 => 1, 1 => 2, 4 => 5] - (retrieved randomly) <a name="method-reduce"></a> #### `reduce()` {#collection-method} `reduce` 方法將每次迭代的結果傳遞給下一次迭代直到集合減少為單個值: $collection = collect([1, 2, 3]); $total = $collection->reduce(function ($carry, $item) { return $carry + $item; }); // 6 第一次迭代時 `$carry` 的數值為 `null`;你也可以通過傳入第二個參數到 `reduce` 來指定它的初始值: $collection->reduce(function ($carry, $item) { return $carry + $item; }, 4); // 10 <a name="method-reject"></a> #### `reject()` {#collection-method} `reject` 方法使用指定的回調過濾集合。如果回調返回 `true` ,就會把對應的項目從集合中移除: $collection = collect([1, 2, 3, 4]); $filtered = $collection->reject(function ($value, $key) { return $value > 2; }); $filtered->all(); // [1, 2] 與 `reject` 相反的方法,查看 [`filter`](#method-filter) 。 <a name="method-reverse"></a> #### `reverse()` {#collection-method} `reverse` 方法倒轉集合中項目的順序: $collection = collect([1, 2, 3, 4, 5]); $reversed = $collection->reverse(); $reversed->all(); // [5, 4, 3, 2, 1] <a name="method-search"></a> #### `search()` {#collection-method} `search` 方法搜索給定的值并返回它的鍵。如果找不到,則返回 `false`: $collection = collect([2, 4, 6, 8]); $collection->search(4); // 1 搜索使用「寬松」比較完成,這意味著具有整數值的字符串會被認為等于相同值的整數。要使用「嚴格」比較,就傳入 `true` 作為該方法的第二個參數: $collection->search('4', true); // false 另外,你可以通過回調來搜索第一個通過真實測試的項目: $collection->search(function ($item, $key) { return $item > 5; }); // 2 <a name="method-shift"></a> #### `shift()` {#collection-method} `shift` 方法移除并返回集合的第一個項目: $collection = collect([1, 2, 3, 4, 5]); $collection->shift(); // 1 $collection->all(); // [2, 3, 4, 5] <a name="method-shuffle"></a> #### `shuffle()` {#collection-method} `shuffle` 方法隨機排序集合中的項目: $collection = collect([1, 2, 3, 4, 5]); $shuffled = $collection->shuffle(); $shuffled->all(); // [3, 2, 5, 1, 4] - (generated randomly) <a name="method-slice"></a> #### `slice()` {#collection-method} `slice` 方法返回集合中給定值后面的部分: $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $slice = $collection->slice(4); $slice->all(); // [5, 6, 7, 8, 9, 10] 如果你想限制返回內容的大小,就將期望的大小作為第二個參數傳遞給方法: $slice = $collection->slice(4, 2); $slice->all(); // [5, 6] 默認情況下,返回的內容將會保留原始鍵。假如你不希望保留原始的鍵,你可以使用 `values` 方法來重新建立索引。 <a name="method-sort"></a> #### `sort()` {#collection-method} `sort` 方法對集合進行排序。排序后的集合保留著原數組的鍵,所以在這個例子中我們使用 [`values`](#method-values) 方法來把鍵重置為連續編號的索引。 $collection = collect([5, 3, 1, 2, 4]); $sorted = $collection->sort(); $sorted->values()->all(); // [1, 2, 3, 4, 5] 如果你有更高級的排序需求,你可以傳入回調來用你自己的算法進行`排序`。請參閱 PHP 文檔的 [`usort`](http://php.net/manual/en/function.usort.php#refsect1-function.usort-parameters),這是集合的 `sort` 方法在底層所調用的。 > {tip} 如果要對嵌套數組或對象的集合進行排序,參考 [`sortBy`](#method-sortby) 和 [`sortByDesc`](#method-sortbydesc) 方法。 <a name="method-sortby"></a> #### `sortBy()` {#collection-method} `sortBy` 方法以給定的鍵對集合進行排序。排序后的集合保留了原數組鍵,所以在這個例子中,我們使用 [`values`](#method-values) 方法將鍵重置為連續編號的索引: $collection = collect([ ['name' => 'Desk', 'price' => 200], ['name' => 'Chair', 'price' => 100], ['name' => 'Bookcase', 'price' => 150], ]); $sorted = $collection->sortBy('price'); $sorted->values()->all(); /* [ ['name' => 'Chair', 'price' => 100], ['name' => 'Bookcase', 'price' => 150], ['name' => 'Desk', 'price' => 200], ] */ 你還可以傳入自己的回調以決定如何對集合的值進行排序: $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(); /* [ ['name' => 'Chair', 'colors' => ['Black']], ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']], ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']], ] */ <a name="method-sortbydesc"></a> #### `sortByDesc()` {#collection-method} 這個方法與 [`sortBy`](#method-sortby) 方法一樣,但是會以相反的順序來對集合進行排序: <a name="method-splice"></a> #### `splice()` {#collection-method} `splice` 方法刪除并返回從給定值后的內容,原集合也會受到影響: $collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2); $chunk->all(); // [3, 4, 5] $collection->all(); // [1, 2] 你可以傳入第二個參數以限制被刪除內容的大小: $collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2, 1); $chunk->all(); // [3] $collection->all(); // [1, 2, 4, 5] 此外,你可以傳入含有新項目的第三個參數來代替集合中刪除的項目: $collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2, 1, [10, 11]); $chunk->all(); // [3] $collection->all(); // [1, 2, 10, 11, 4, 5] <a name="method-split"></a> #### `split()` {#collection-method} `split` 方法將集合按給定的值拆分: $collection = collect([1, 2, 3, 4, 5]); $groups = $collection->split(3); $groups->toArray(); // [[1, 2], [3, 4], [5]] <a name="method-sum"></a> #### `sum()` {#collection-method} `sum` 方法返回集合內所有項目的總和: collect([1, 2, 3, 4, 5])->sum(); // 15 如果集合包含嵌套數組或對象,則應該傳入一個鍵來指定要進行求和的值: $collection = collect([ ['name' => 'JavaScript: The Good Parts', 'pages' => 176], ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096], ]); $collection->sum('pages'); // 1272 另外,你也可以傳入回調來決定要用集合中的哪些值進行求和: $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']); }); // 6 <a name="method-take"></a> #### `take()` {#collection-method} `take` 方法返回給定數量項目的新集合: $collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(3); $chunk->all(); // [0, 1, 2] 你也可以傳入負整數從集合末尾開始獲取指定數量的項目: $collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(-2); $chunk->all(); // [4, 5] <a name="method-tap"></a> #### `tap()` {#collection-method} `tap` 方法將集合傳遞給回調,在特定點「tap」集合。此舉能讓你對集合中的項目執行某些操作,而不影響集合本身: collect([2, 4, 3, 1, 5]) ->sort() ->tap(function ($collection) { Log::debug('Values after sorting', $collection->values()->toArray()); }) ->shift(); // 1 <a name="method-times"></a> #### `times()` {#collection-method} 靜態 `times` 方法通過回調在給定次數內創建一個新的集合: $collection = Collection::times(10, function ($number) { return $number * 9; }); $collection->all(); // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90] 使用這個方法可以與工廠結合使用創建出 [Eloquent](/docs/{{version}}/eloquent) 模型: $categories = Collection::times(3, function ($number) { return factory(Category::class)->create(['name' => 'Category #'.$number]); }); $categories->all(); /* [ ['id' => 1, 'name' => 'Category #1'], ['id' => 2, 'name' => 'Category #2'], ['id' => 3, 'name' => 'Category #3'], ] */ <a name="method-toarray"></a> #### `toArray()` {#collection-method} `toArray` 方法將集合轉換成 PHP `數組`。如果集合的值是 [Eloquent](/docs/{{version}}/eloquent) 模型,那也會被轉換成數組: $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* [ ['name' => 'Desk', 'price' => 200], ] */ > {note} `toArray` 也會將所有集合的嵌套對象轉換為數組。如果你想獲取原數組,就改用 [`all`](#method-all) 方法。 <a name="method-tojson"></a> #### `toJson()` {#collection-method} `toJson` 方法將集合轉換成 JSON 字符串: $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toJson(); // '{"name":"Desk", "price":200}' <a name="method-transform"></a> #### `transform()` {#collection-method} `transform` 方法迭代集合并對集合內的每個項目調用給定的回調。而集合的內容也會被回調返回的值取代: $collection = collect([1, 2, 3, 4, 5]); $collection->transform(function ($item, $key) { return $item * 2; }); $collection->all(); // [2, 4, 6, 8, 10] > {note} 與大多數集合的方法不同,`transform` 會修改集合本身。如果你想創建新的集合,就改用 [`map`](#method-map) 方法。 <a name="method-union"></a> #### `union()` {#collection-method} `unique` 方法將給定的數組添加到集合中。如果給定的數組中含有與原集合一樣的鍵,則原集合的值不會被改變: $collection = collect([1 => ['a'], 2 => ['b']]); $union = $collection->union([3 => ['c'], 1 => ['b']]); $union->all(); // [1 => ['a'], 2 => ['b'], 3 => ['c']] <a name="method-unique"></a> #### `unique()` {#collection-method} `unique` 方法返回集合中所有唯一的項目。返回的集合保留著原數組的鍵,所以在這個例子中,我們使用 [`values`](#method-values) 方法來把鍵重置為連續編號的索引。 $collection = collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4] 處理嵌套數組或對象時,你可以指定用來決定唯一性的鍵: $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(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ] */ 你也可以傳入自己的回調來確定項目的唯一性: $unique = $collection->unique(function ($item) { return $item['brand'].$item['type']; }); $unique->values()->all(); /* [ ['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'], ] */ 在檢查項目值時 `unique` 方法使用的是「寬松」比較,意味著具有整數值的字符串將被視為等于相同值的整數。使用 [`uniqueStrict`](#method-uniquestrict) 可以進行「嚴格」比較 。 <a name="method-uniquestrict"></a> #### `uniqueStrict()` {#collection-method} 這個方法的使用和 [`unique`](#method-unique) 方法類似,只是使用了「嚴格」比較來過濾。 <a name="method-values"></a> #### `values()` {#collection-method} `values` 方法返回鍵被重置為連續編號的新集合: $collection = collect([ 10 => ['product' => 'Desk', 'price' => 200], 11 => ['product' => 'Desk', 'price' => 200] ]); $values = $collection->values(); $values->all(); /* [ 0 => ['product' => 'Desk', 'price' => 200], 1 => ['product' => 'Desk', 'price' => 200], ] */ <a name="method-when"></a> #### `when()` {#collection-method} `when` 方法當傳入的第一個參數為 `true` 的時,將執行給定的回調: $collection = collect([1, 2, 3]); $collection->when(true, function ($collection) { return $collection->push(4); }); $collection->all(); // [1, 2, 3, 4] <a name="method-where"></a> #### `where()` {#collection-method} `where` 方法通過給定的鍵值過濾集合: $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(); /* [ ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100], ] */ 比較數值的時候,`where` 方法使用「寬松」比較,意味著具有整數值的字符串將被認為等于相同值的整數。使用 [`whereStrict`](#method-wherestrict) 方法來進行「嚴格」比較過濾。 <a name="method-wherestrict"></a> #### `whereStrict()` {#collection-method} 這個方法與 [`where`](#method-where) 方法一樣;但是會以「嚴格」比較來匹配所有值: <a name="method-wherein"></a> #### `whereIn()` {#collection-method} `whereIn` 方法通過給定的鍵值數組來過濾集合: $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(); /* [ ['product' => 'Bookcase', 'price' => 150], ['product' => 'Desk', 'price' => 200], ] */ `whereIn` 方法在檢查項目值時使用「寬松」比較,意味著具有整數值的字符串將被視為等于相同值的整數。你可以使用 [`whereInStrict`](#method-whereinstrict) 做「嚴格」比較。 <a name="method-whereinstrict"></a> #### `whereInStrict()` {#collection-method} 此方法的使用和 [`whereIn`](#method-wherein) 方法類似,只是使用了「嚴格」比較來匹配所有值。 <a name="method-wherenotin"></a> #### `whereNotIn()` {#collection-method} `whereNotIn` 通過集合中不包含的給定鍵值對進行: $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(); /* [ ['product' => 'Chair', 'price' => 100], ['product' => 'Door', 'price' => 100], ] */ `whereNotIn` 方法在檢查項目值時使用「寬松」比較,意味著具有整數值的字符串將被視為等于相同值的整數。你可以使用 [`whereNotInStrict`](#method-wherenotinstrict) 做比較 `嚴格` 的匹配。 <a name="method-wherenotinstrict"></a> #### `whereNotInStrict()` {#collection-method} 此方法的使用和 [`whereNotIn`](#method-wherenotin) 方法類似,只是使用了「嚴格」比較來匹配所有值。 <a name="method-zip"></a> #### `zip()` {#collection-method} `zip` 方法將給定數組的值與相應索引處的原集合的值合并在一起: $collection = collect(['Chair', 'Desk']); $zipped = $collection->zip([100, 200]); $zipped->all(); // [['Chair', 100], ['Desk', 200]] <a name="higher-order-messages"></a> ## 高階消息傳遞 集合也提供對「高階消息傳遞」的支持,即對集合執行常見操作的快捷方式。支持高階消息傳遞的集合方法有:`average`, `avg`, `contains`, `each`, `every`, `filter`, `first`, `flatMap`, `map`, `partition`, `reject`, `sortBy`, `sortByDesc` 和 `sum`。 每個高階消息都能作為集合實例的動態屬性來訪問。例如,使用 `each` 高階消息傳遞在集合中的每個對象上調用一個方法: $users = User::where('votes', '>', 500)->get(); $users->each->markAsVip(); 同樣,我們可以使用 `sum` 高階消息來收集集合中「投票」總數: $users = User::where('group', 'Development')->get(); return $users->sum->votes; --- > {note} 歡迎任何形式的轉載,但請務必注明出處,尊重他人勞動共創開源社區。 > > 轉載請注明:本文檔由 Laravel China 社區 [laravel-china.org](https://laravel-china.org) 組織翻譯,詳見 [翻譯召集帖](https://laravel-china.org/topics/5756/laravel-55-document-translation-call-come-and-join-the-translation)。 > > 文檔永久地址: https://d.laravel-china.org
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看