集合
📝 此頁面為 Laravel 官方文檔的繁體中文翻譯。查看原始英文版本
集合
簡介
Illuminate\Support\Collection 類別為處理資料陣列提供了一個流暢、便利的包裝器。例如,查看以下程式碼。我們將使用 collect 輔助函數從陣列建立一個新的集合實例,對每個元素運行 strtoupper 函數,然後移除所有空元素:
$collection = collect(['Taylor', 'Abigail', null])->map(function (?string $name) {
return strtoupper($name);
})->reject(function (string $name) {
return empty($name);
});
如您所見,Collection 類別允許您鏈接其方法以對底層陣列執行流暢的映射和歸約操作。通常,集合是不可變的,這意味著每個 Collection 方法都返回一個全新的 Collection 實例。
建立集合
如上所述,collect 輔助函數為給定的陣列返回一個新的 Illuminate\Support\Collection 實例。因此,建立集合就像這樣簡單:
$collection = collect([1, 2, 3]);
您還可以使用 make 和 fromJson 方法建立集合。
[!NOTE] Eloquent 查詢的結果總是作為
Collection實例返回。
擴展集合
集合是「可宏的」,這允許您在運行時向 Collection 類別添加額外的方法。Illuminate\Support\Collection 類別的 macro 方法接受一個閉包,該閉包將在調用您的宏時執行。宏閉包可以透過 $this 存取集合的其他方法,就像它是集合類別的真實方法一樣。例如,以下程式碼向 Collection 類別添加了一個 toUpper 方法:
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
Collection::macro('toUpper', function () {
return $this->map(function (string $value) {
return Str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toUpper();
// ['FIRST', 'SECOND']
通常,您應該在服務提供者的 boot 方法中聲明集合宏。
宏參數
如有必要,您可以定義接受額外參數的宏:
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Lang;
Collection::macro('toLocale', function (string $locale) {
return $this->map(function (string $value) use ($locale) {
return Lang::get($value, [], $locale);
});
});
$collection = collect(['first', 'second']);
$translated = $collection->toLocale('es');
// ['primero', 'segundo'];
可用方法
對於其餘大部分集合文檔,我們將討論 Collection 類別上可用的每個方法。請記住,所有這些方法都可以鏈接使用來流暢地操作底層陣列。此外,幾乎每個方法都返回一個新的 Collection 實例,允許您在必要時保留集合的原始副本:
after all average avg before chunk chunkWhile collapse collapseWithKeys collect combine concat contains containsStrict count countBy crossJoin dd diff diffAssoc diffAssocUsing diffKeys doesntContain doesntContainStrict dot dump duplicates duplicatesStrict each eachSpread ensure every except filter first firstOrFail firstWhere flatMap flatten flip forget forPage fromJson get groupBy has hasAny hasMany hasSole implode intersect intersectUsing intersectAssoc intersectAssocUsing intersectByKeys isEmpty isNotEmpty join keyBy keys last lazy macro make map mapInto mapSpread mapToGroups mapWithKeys max median merge mergeRecursive min mode multiply nth only pad partition percentage pipe pipeInto pipeThrough pluck pop prepend pull push put random range reduce reduceSpread reject replace replaceRecursive reverse search select shift shuffle skip skipUntil skipWhile slice sliding sole some sort sortBy sortByDesc sortDesc sortKeys sortKeysDesc sortKeysUsing splice split splitIn sum take takeUntil takeWhile tap times toArray toJson toPrettyJson transform undot union unique uniqueStrict unless unlessEmpty unlessNotEmpty unwrap value values when whenEmpty whenNotEmpty where whereStrict whereBetween whereIn whereInStrict whereInstanceOf whereNotBetween whereNotIn whereNotInStrict whereNotNull whereNull wrap zip
方法列表
after() {.collection-method .first-collection-method}
after 方法返回給定項目之後的項目。如果未找到給定的項目或它是最後一個項目,則返回 null:
$collection = collect([1, 2, 3, 4, 5]);
$collection->after(3);
// 4
$collection->after(5);
// null
此方法使用「鬆散」比較搜尋給定的項目,這意味著包含整數值的字串將被認為等於相同值的整數。要使用「嚴格」比較,您可以向方法提供 strict 參數:
collect([2, 4, 6, 8])->after('4', strict: true);
// null
或者,您可以提供自己的閉包來搜尋通過給定真值測試的第一個項目:
collect([2, 4, 6, 8])->after(function (int $item, int $key) {
return $item > 5;
});
// 8
all() {.collection-method}
all 方法返回集合所表示的底層陣列:
collect([1, 2, 3])->all();
// [1, 2, 3]
average() {.collection-method}
avg 方法的別名。
avg() {.collection-method}
avg 方法返回給定金鑰的平均值:
$average = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->avg('foo');
// 20
$average = collect([1, 1, 2, 4])->avg();
// 2
before() {.collection-method}
before 方法是 after 方法的相反。它返回給定項目之前的項目。如果未找到給定的項目或它是第一個項目,則返回 null:
$collection = collect([1, 2, 3, 4, 5]);
$collection->before(3);
// 2
$collection->before(1);
// null
collect([2, 4, 6, 8])->before('4', strict: true);
// null
collect([2, 4, 6, 8])->before(function (int $item, int $key) {
return $item > 5;
});
// 4
chunk() {.collection-method}
chunk 方法將集合分割為多個給定大小的較小集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->all();
// [[1, 2, 3, 4], [5, 6, 7]]
此方法在處理如 Bootstrap 這樣的格線系統時,在視圖中特別有用。例如,想像您有一個Eloquent 模型集合,您想在格線中顯示:
@foreach ($products->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $product)
<div class="col-xs-4">{{ $product->name }}</div>
@endforeach
</div>
@endforeach
chunkWhile() {.collection-method}
chunkWhile 方法根據給定回呼的評估將集合分割為多個較小的集合。傳遞給閉包的 $chunk 變數可用於檢查前一個元素:
$collection = collect(str_split('AABBCCCD'));
$chunks = $collection->chunkWhile(function (string $value, int $key, Collection $chunk) {
return $value === $chunk->last();
});
$chunks->all();
// [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]
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]
collapseWithKeys() {.collection-method}
collapseWithKeys 方法將一個陣列或集合的集合展平為一個集合,保留原始金鑰。如果集合已經是扁平的,則返回一個空集合:
$collection = collect([
['first' => collect([1, 2, 3])],
['second' => [4, 5, 6]],
['third' => collect([7, 8, 9])]
]);
$collapsed = $collection->collapseWithKeys();
$collapsed->all();
// [
// 'first' => [1, 2, 3],
// 'second' => [4, 5, 6],
// 'third' => [7, 8, 9],
// ]
collect() {.collection-method}
collect 方法返回一個包含集合中當前項目的新 Collection 實例:
$collectionA = collect([1, 2, 3]);
$collectionB = $collectionA->collect();
$collectionB->all();
// [1, 2, 3]
collect 方法主要用於將延遲集合轉換為標準 Collection 實例:
$lazyCollection = LazyCollection::make(function () {
yield 1;
yield 2;
yield 3;
});
$collection = $lazyCollection->collect();
$collection::class;
// 'Illuminate\Support\Collection'
$collection->all();
// [1, 2, 3]
[!NOTE]
collect方法在您有一個Enumerable實例且需要一個非延遲集合實例時特別有用。由於collect()是Enumerable合約的一部分,您可以安全地使用它來獲取Collection實例。
combine() {.collection-method}
combine 方法將集合的值作為金鑰,與另一個陣列或集合的值組合:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
concat() {.collection-method}
concat 方法將給定的陣列或集合的值附加到另一個集合的末尾:
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']
concat 方法為附加到原始集合的項目重新索引金鑰。要在關聯集合中保留金鑰,請參閱 merge 方法。
contains() {.collection-method}
contains 方法判斷集合是否包含給定的項目。您可以向 contains 方法傳遞一個閉包來判斷集合中是否存在匹配給定真值測試的元素:
$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function (int $value, int $key) {
return $value > 5;
});
// false
或者,您可以向 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 方法在檢查項目值時使用「鬆散」比較,這意味著包含整數值的字串將被認為等於相同值的整數。使用 containsStrict 方法使用「嚴格」比較進行篩選。
有關 contains 的相反操作,請參閱 doesntContain 方法。
containsStrict() {.collection-method}
此方法具有與 contains 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。
[!NOTE] 使用 Eloquent 集合時,此方法的行為會被修改。
count() {.collection-method}
count 方法返回集合中項目的總數:
$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4
countBy() {.collection-method}
countBy 方法計算集合中值的出現次數。預設情況下,該方法計算每個元素的出現次數,允許您計算集合中某些「類型」的元素:
$collection = collect([1, 2, 2, 2, 3]);
$counted = $collection->countBy();
$counted->all();
// [1 => 1, 2 => 3, 3 => 1]
您可以向 countBy 方法傳遞一個閉包來按自訂值計算所有項目:
$collection = collect(['[email protected]', '[email protected]', '[email protected]']);
$counted = $collection->countBy(function (string $email) {
return substr(strrchr($email, '@'), 1);
});
$counted->all();
// ['gmail.com' => 2, 'yahoo.com' => 1]
crossJoin() {.collection-method}
crossJoin 方法交叉連接集合的值與給定的陣列或集合,返回一個包含所有可能排列的笛卡爾乘積:
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b']);
$matrix->all();
/*
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
]
*/
$collection = collect([1, 2]);
$matrix = $collection->crossJoin(['a', 'b'], ['I', 'II']);
$matrix->all();
/*
[
[1, 'a', 'I'],
[1, 'a', 'II'],
[1, 'b', 'I'],
[1, 'b', 'II'],
[2, 'a', 'I'],
[2, 'a', 'II'],
[2, 'b', 'I'],
[2, 'b', 'II'],
]
*/
dd() {.collection-method}
dd 方法轉儲集合的項目並終止腳本的執行:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
*/
如果您不想停止腳本的執行,請改用 dump 方法。
diff() {.collection-method}
diff 方法根據值將集合與另一個集合或普通 PHP array 進行比較。此方法將返回原始集合中不存在於給定集合中的值:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
[!NOTE] 使用 Eloquent 集合時,此方法的行為會被修改。
diffAssoc() {.collection-method}
diffAssoc 方法根據金鑰和值將集合與另一個集合或普通 PHP array 進行比較。此方法將返回原始集合中不存在於給定集合中的金鑰/值對:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$other = collect([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 5,
]);
$diff = $collection->diffAssoc($other);
$diff->all();
// ['color' => 'orange', 'remain' => 6, 'used' => 5]
diffAssocUsing() {.collection-method}
diffAssocUsing 方法使用給定的回呼進行金鑰比較,將集合與另一個集合或普通 PHP array 進行比較:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$other = collect([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 5,
]);
$diff = $collection->diffAssocUsing($other, 'strnatcasecmp');
$diff->all();
// ['color' => 'orange', 'remain' => 6, 'used' => 5]
diffKeys() {.collection-method}
diffKeys 方法根據金鑰將集合與另一個集合或普通 PHP array 進行比較。此方法將返回原始集合中不存在於給定集合中的金鑰/值對:
$collection = collect([
'one' => 10,
'two' => 20,
'three' => 30,
]);
$diff = $collection->diffKeys([
'two' => 21,
'three' => 30,
]);
$diff->all();
// ['one' => 10]
doesntContain() {.collection-method}
doesntContain 方法判斷集合是否不包含給定的項目。您可以向 doesntContain 方法傳遞一個閉包來判斷集合中是否存在匹配給定真值測試的元素:
$collection = collect([1, 2, 3, 4, 5]);
$collection->doesntContain(function (int $value, int $key) {
return $value > 5;
});
// true
或者,您可以向 doesntContain 方法傳遞一個字串來判斷集合是否不包含給定的項目值:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->doesntContain('Desk');
// false
$collection->doesntContain('New York');
// true
您還可以向 doesntContain 方法傳遞一個金鑰/值對,這將判斷給定的對是否存在於集合中:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->doesntContain('product', 'Bookcase');
// true
doesntContain 方法在檢查項目值時使用「鬆散」比較,這意味著包含整數值的字串將被認為等於相同值的整數。使用 doesntContainStrict 方法使用「嚴格」比較進行篩選。
有關 doesntContain 的相反操作,請參閱 contains 方法。
doesntContainStrict() {.collection-method}
此方法具有與 doesntContain 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。
[!NOTE] 使用 Eloquent 集合時,此方法的行為會被修改。
dot() {.collection-method}
dot 方法將多維集合展平為使用「點」語法表示深度的單層陣列:
$collection = collect([
'name' => 'Taylor',
'languages' => [
'php' => [
'laravel' => [
'forge' => 'vapor',
],
],
],
]);
$flattened = $collection->dot();
$flattened->all();
// ['name' => 'Taylor', 'languages.php.laravel.forge' => 'vapor']
dump() {.collection-method}
dump 方法轉儲集合的項目:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dump();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
如果您想停止腳本的執行,請改用 dd 方法。
duplicates() {.collection-method}
duplicates 方法檢索集合中的重複值:
$collection = collect(['foo', 'bar', 'foo', 'baz']);
$collection->duplicates();
// [2 => 'foo']
如果集合包含陣列或物件,您可以指定用於確定唯一性的金鑰:
$employees = collect([
['name' => 'Taylor Otwell', 'department' => 'IT'],
['name' => 'Otwell Taylor', 'department' => 'IT'],
['name' => 'John Doe', 'department' => 'Marketing'],
]);
$employees->duplicates('department');
// [0 => 'IT', 1 => 'IT']
duplicatesStrict() {.collection-method}
此方法具有與 duplicates 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。
each() {.collection-method}
each 方法遍歷集合中的項目,將每個項目傳遞給回呼:
$collection = collect([1, 2, 3, 4]);
$collection->each(function (int $item, int $key) {
//
});
如果要從回呼中停止遍歷集合中的其餘項目,您的回呼應返回 false:
$collection->each(function (int $item, int $key) {
if ($key === 1) {
return false;
}
});
eachSpread() {.collection-method}
eachSpread 方法遍歷集合中的項目,將每個展開的參數傳遞給回呼:
$collection = collect([['Taylor', 'Otwell'], ['Dayle', 'Rees']]);
$collection->eachSpread(function (string $firstName, string $lastName) {
//
});
如果要從回呼中停止遍歷集合中的其餘項目,您的回呼應返回 false:
$collection->eachSpread(function (string $firstName, string $lastName, int $key) {
if ($key === 0) {
return false;
}
});
ensure() {.collection-method}
ensure 方法驗證集合中包含給定金鑰和類型的項目。如果集合中不存在給定的金鑰,或者給定金鑰的值類型不正確,將會拋出異常:
use App\Models\User;
use Illuminate\Support\Collection;
$collection = User::all()->ensure(Author::class);
$collection = collect(['string', User::find(1)])->ensure(['string', 'integer']);
如果給定的金鑰的值類型不正確,將會拋出 TypeError。如果沒有指定金鑰,或者集合中不存在給定的金鑰,將會拋出 InvalidArgumentException。
every() {.collection-method}
every 方法驗證集合中的所有元素是否通過給定的真值測試:
collect([1, 2, 3, 4])->every(function (int $value, int $key) {
return $value > 2;
});
// false
except() {.collection-method}
except 方法返回集合中不具有給定金鑰的所有項目:
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => 15]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]
except 方法的相反操作是 only 方法。
filter() {.collection-method}
filter 方法使用給定的回呼過濾集合,保留通過真值測試的項目:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function (int $value, int $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]
如果不向 filter 方法傳遞回呼,它將返回集合中所有不是 false、null 或 0 的項目:
$collection = collect([1, 2, 3, 0, null, false, '']);
$collection->filter()->all();
// [1, 2, 3]
first() {.collection-method}
first 方法返回通過給定真值測試的集合的第一個元素:
$collection = collect([1, 2, 3, 4]);
$collection->first(function (int $value, int $key) {
return $value > 2;
});
// 3
您可以向 first 方法傳遞一個預設值。如果沒有值通過真值測試,將返回此值:
$collection = collect([1, 2, 3, 4]);
$collection->first(function (int $value, int $key) {
return $value > 10;
}, 5);
// 5
firstOrFail() {.collection-method}
firstOrFail 方法返回通過給定真值測試的集合的第一個元素,但如果未找到任何匹配的項目,則會拋出異常:
collect([1, 2, 3, 4])->firstOrFail(function (int $value) {
return $value > 5;
});
// 會拋出 ItemNotFoundException
firstWhere() {.collection-method}
firstWhere 方法返回與給定鍵值對匹配的集合的第一個元素:
$collection = collect([
['name' => 'Taylor', 'active' => true],
['name' => 'Dayle', 'active' => false],
]);
$collection->firstWhere('name', 'Taylor');
// ['name' => 'Taylor', 'active' => true]
您還可以使用「點」語法向 firstWhere 方法傳遞一個條件:
$collection->firstWhere('address.zip', '72212');
// ['name' => 'Taylor', 'email' => '[email protected]', 'address' => ['city' => 'Portland', 'zip' => '72212']]
flatMap() {.collection-method}
flatMap 方法遍歷集合中的項目,將每個展開的參數傳遞給回呼,然後將結果展平為單一陣列:
$collection = collect([
['name' => 'Taylor'],
['name' => 'Dayle'],
]);
$flattened = $collection->flatMap(function (array $values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['Taylor', 'Dayle']
flatten() {.collection-method}
flatten 方法將多維集合展平為單一陣列:
$collection = collect([
'name' => 'Taylor',
'languages' => [
'php',
'javascript',
],
]);
$flattened = $collection->flatten();
$flattened->all();
// ['Taylor', 'php', 'javascript']
您可以選擇向 flatten 方法提供「深度」參數來限制展平的程度:
$collection = collect([
'name' => 'Taylor',
'languages' => [
'php' => [
'laravel',
'forge',
],
],
]);
$flattened = $collection->flatten(1);
$flattened->all();
// ['Taylor', 'php', ['laravel', 'forge']]
flip() {.collection-method}
flip 方法交換集合的金鑰和值:
$collection = collect(['name' => 'Taylor', 'framework' => 'Laravel']);
$flipped = $collection->flip();
$flipped->all();
// ['Taylor' => 'name', 'Laravel' => 'framework']
forget() {.collection-method}
forget 方法從集合中移除給定金鑰的項目:
$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => 15]);
$collection->forget('price');
$collection->all();
// ['product_id' => 1, 'discount' => 15]
forget 方法的相反操作是 pull 方法。
forPage() {.collection-method}
forPage 方法返回給定頁碼的項目集合。此方法要求頁碼從 1 開始,每頁的項目數從 1 開始:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$collection->forPage(2, 3)->all();
// [4, 5, 6]
fromJson() {.collection-method}
fromJson 方法從給定的 JSON 字串建立一個集合:
$collection = Collection::fromJson('[1,2,3]');
$collection->all();
// [1, 2, 3]
get() {.collection-method}
get 方法返回給定金鑰的項目,如果金鑰不存在,則返回預設值:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->get('name');
// 'Desk'
$collection->get('price', 0);
// 0
groupBy() {.collection-method}
groupBy 方法根據給定的金鑰或回呼將集合中的項目分組:
$collection = collect([
['account_id' => 1, 'product' => 'Desk', 'amount' => 50],
['account_id' => 2, 'product' => 'Chair', 'amount' => 200],
['account_id' => 1, 'product' => 'Bookcase', 'amount' => 65],
['account_id' => 2, 'product' => 'Armchair', 'amount' => 150],
]);
$grouped = $collection->groupBy('account_id');
$grouped->all();
/*
[
1 => [
['account_id' => 1, 'product' => 'Desk', 'amount' => 50],
['account_id' => 1, 'product' => 'Bookcase', 'amount' => 65],
],
2 => [
['account_id' => 2, 'product' => 'Chair', 'amount' => 200],
['account_id' => 2, 'product' => 'Armchair', 'amount' => 150],
],
]
*/
除了金鑰名稱之外,您還可以傳遞一個回呼來確定金鑰的值:
$grouped = $collection->groupBy(function (array $item, int $key) {
return substr($item['product'], 0, 3);
});
$grouped->all();
/*
[
'Des' => [
['account_id' => 1, 'product' => 'Desk', 'amount' => 50],
],
'Chi' => [
['account_id' => 2, 'product' => 'Chair', 'amount' => 200],
],
'Boo' => [
['account_id' => 1, 'product' => 'Bookcase', 'amount' => 65],
],
'Arm' => [
['account_id' => 2, 'product' => 'Armchair', 'amount' => 150],
],
]
*/
has() {.collection-method}
has 方法判斷集合是否包含給定的金鑰:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->has('product_id');
// true
$collection->has('product_id', 'name');
// true
$collection->has(['name', 'price']);
// false
hasAny() {.collection-method}
hasAny 方法判斷集合是否包含任何給定的金鑰:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->hasAny(['name', 'price']);
// true
hasMany() {.collection-method}
hasMany 方法判斷集合是否包含所有給定的金鑰:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->hasMany(['name', 'price']);
// false
hasSole() {.collection-method}
hasSole 方法判斷集合是否恰好包含給定的金鑰之一:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->hasSole(['name', 'price']);
// true
$collection->hasSole(['name', 'product_id']);
// false
implode() {.collection-method}
implode 方法使用字串連接集合中的項目。您可以傳遞一個陣列的金鑰和連接字元,或者一個回呼:
$collection = collect([
['account_id' => 1, 'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk,Chair
$collection->implode(function (array $item, int $key) {
return $item['product'];
});
// DeskChair
如果集合包含簡單的字串或整數,您可以直接傳遞連接字元:
collect([1, 2, 3, 4, 5])->implode('-');
// 1-2-3-4-5
intersect() {.collection-method}
intersect 方法從另一個陣列或集合中移除不在集合中的所有值。結果集合保留原始集合的金鑰:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$filtered = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$filtered->all();
// ['name' => 'Desk']
intersectUsing() {.collection-method}
intersectUsing 方法從另一個陣列或集合中移除不在集合中的所有值,使用給定的回呼來比較值:
$collection = collect(['name' => 'Desk', 'price' => 100]);
$filtered = $collection->intersectUsing(['desk', 'chair', 'bookcase'], 'strcasecmp');
$filtered->all();
// ['name' => 'Desk']
intersectAssoc() {.collection-method}
intersectAssoc 方法從另一個陣列或集合中移除不在集合中的所有金鑰/值對:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$other = collect([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 5,
]);
$diff = $collection->intersectAssoc($other);
$diff->all();
// ['type' => 'fruit', 'remain' => 6]
intersectAssocUsing() {.collection-method}
intersectAssocUsing 方法從另一個陣列或集合中移除不在集合中的所有金鑰/值對,使用給定的回呼來比較值:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6,
]);
$other = collect([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 5,
]);
$diff = $collection->intersectAssocUsing($other, 'strnatcasecmp');
$diff->all();
// ['type' => 'fruit', 'remain' => 6]
intersectByKeys() {.collection-method}
intersectByKeys 方法從另一個陣列或集合中移除不在集合中的所有金鑰:
$collection = collect([
'serial' => '1',
'title' => 'The Name of the Wind',
'author' => 'Patrick Rothfuss',
]);
$filtered = $collection->intersectByKeys([
'serial' => '1',
'author' => 'Patrick Rothfuss',
]);
$filtered->all();
// ['serial' => '1', 'author' => 'Patrick Rothfuss']
isEmpty() {.collection-method}
isEmpty 方法判斷集合是否為空:
collect([])->isEmpty();
// true
isEmpty 方法的相反操作是 isNotEmpty 方法。
isNotEmpty() {.collection-method}
isNotEmpty 方法判斷集合是否不為空:
collect([])->isNotEmpty();
// false
join() {.collection-method}
join 方法使用字串連接集合中的項目:
$collection = collect(['Taylor', 'Dayle', 'Matt']);
$collection->join(', ', ' and ');
// "Taylor, Dayle and Matt"
您可以使用第三個參數指定最後一個項目之前使用的字串:
$collection = collect(['Taylor', 'Dayle']);
$collection->join(', ', ' and ');
// "Taylor and Dayle"
keyBy() {.collection-method}
keyBy 方法使用給定的金鑰為集合設定金鑰:
$collection = collect([
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
]);
$keyed = $collection->keyBy('name');
$keyed->all();
/*
[
'Alice' => ['id' => 1, 'name' => 'Alice'],
'Bob' => ['id' => 2, 'name' => 'Bob'],
]
*/
keys() {.collection-method}
keys 方法返回集合中的所有金鑰:
$collection = collect([
'name' => 'Taylor',
'framework' => 'Laravel',
]);
$keys = $collection->keys();
$keys->all();
// ['name', 'framework']
last() {.collection-method}
last 方法返回通過給定真值測試的集合的最後一個元素:
$collection = collect([1, 2, 3, 4]);
$collection->last(function (int $value, int $key) {
return $value < 2;
});
// 1
lazy() {.collection-method}
lazy 方法從給定的陣列建立一個延遲集合:
$collection = collect(['Taylor', 'Dayle'])->lazy();
$collection::class;
// 'Illuminate\Support\LazyCollection'
$collection->toArray();
// ['Taylor', 'Dayle']
macro() {.collection-method}
macro 方法在 Collection 類別上靜態地註冊一個宏:
use Illuminate\Support\Collection;
Collection::macro('toUpperCase', function () {
return $this->map(function (string $value) {
return strtoupper($value);
});
});
$collection = collect(['first', 'second', 'third']);
$collection->toUpperCase();
// ['FIRST', 'SECOND', 'THIRD']
make() {.collection-method}
make 方法從給定的值建立一個新的 Collection 實例:
use Illuminate\Support\Collection;
$collection = Collection::make('Taylor');
$collection->all();
// ['Taylor']
map() {.collection-method}
map 方法遍歷集合中的項目,將每個項目傳遞給回呼。集合由回呼返回的值取代:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function (int $item, int $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
[!NOTE] 使用 Eloquent 集合時,
map方法保留模型的金鑰。
mapInto() {.collection-method}
mapInto 方法遍歷集合中的項目,將每個展開的參數傳遞給回呼,使用結果填充新的實例:
$collection = collect(['class-1', 'class-2', 'class-3']);
$collection->mapInto(CssClass::class);
mapSpread() {.collection-method}
mapSpread 方法遍歷集合中的項目,將每個展開的參數傳遞給回呼,然後使用結果填充一個新的實例:
$collection = collect([
[15, 25, 35],
[10, 20, 30],
]);
$collection->mapSpread(function (int $odd, int $even, int $key) {
return $odd + $even;
});
// [40, 30]
mapToGroups() {.collection-method}
mapToGroups 方法遍歷集合中的項目,將每個展開的參數傳遞給回呼,使用結果填充一個以鍵分組的新集合:
$collection = collect([
['name' => 'John Doe', 'department' => 'Sales'],
['name' => 'Jane Doe', 'department' => 'Marketing'],
['name' => 'Bob Doe', 'department' => 'Sales'],
]);
$grouped = $collection->mapToGroups(function (array $item, int $key) {
return [$item['department'] => $item['name']];
});
$grouped->all();
// [
// 'Sales' => ['John Doe', 'Bob Doe'],
// 'Marketing' => ['Jane Doe'],
// ]
mapWithKeys() {.collection-method}
mapWithKeys 方法遍歷集合中的項目,將每個展開的參數傳遞給回呼,然後將結果填充為一個新的集合:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'enrolled' => '2013-01-01',
],
[
'name' => 'Alice',
'department' => 'Marketing',
'enrolled' => '2014-03-22',
],
]);
$collection->mapWithKeys(function (array $item, int $key) {
return [$item['name'] => $item['department']];
});
// ['John' => 'Sales', 'Alice' => 'Marketing']
max() {.collection-method}
max 方法返回給定金鑰的最大值:
$max = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->max('foo');
// 40
median() {.collection-method}
median 方法返回給定金鑰的中位數值:
$median = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->median('foo');
// 15
merge() {.collection-method}
merge 方法將給定的陣列或集合的值合併到另一個集合中。如果給定的陣列或集合中的金鑰與原始集合中的金鑰衝突,則給定陣列或集合的值將覆蓋原始集合中的值:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$merged = $collection->merge(['price' => 100, 'discount' => 15]);
$merged->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => 15]
如果給定陣列或集合中的金鑰是數字,則值將被附加到集合的末尾:
$collection = collect(['Dayle', 'Matt', 'Jeff']);
$merged = $collection->merge(['Taylor', 'Otwell']);
$merged->all();
// ['Dayle', 'Matt', 'Jeff', 'Taylor', 'Otwell']
mergeRecursive() {.collection-method}
mergeRecursive 方法遞歸合併給定的陣列或集合到另一個集合中。如果給定的陣列或集合中的金鑰與原始集合中的金鑰衝突,則值將合併到一個陣列中:
$collection = collect([
'name' => 'John Doe',
'books' => [
'PHP',
],
]);
$collection = $collection->mergeRecursive([
'name' => 'Jane Doe',
'books' => [
'Laravel',
],
]);
$collection->all();
// ['name' => ['John Doe', 'Jane Doe'], 'books' => ['PHP', 'Laravel']]
min() {.collection-method}
min 方法返回給定金鑰的最小值:
$min = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->min('foo');
// 10
mode() {.collection-method}
mode 方法返回給定金鑰的眾數值:
$mode = collect([
['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]
])->mode('foo');
// [10]
multiply() {.collection-method}
multiply 方法建立一個新的空集合,並使用給定的值和計數填充它:
$collection = collect()->multiply('foo', 3);
$collection->all();
// ['foo', 'foo', 'foo']
nth() {.collection-method}
nth 方法返回集合中每個第 n 個元素:
$collection = collect([
'a', 'b', 'c', 'd', 'e', 'f'
]);
$collection->nth(4);
// ['a', 'e']
您可以選擇從給定的偏移量開始:
$collection->nth(4, 2);
// ['c', 'g']
only() {.collection-method}
only 方法返回具有給定金鑰的項目。此方法的相反操作是 except 方法:
$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100]);
$filtered = $collection->only(['name', 'price']);
$filtered->all();
// ['name' => 'Desk', 'price' => 100]
pad() {.collection-method}
pad 方法使用給定的值填充集合到給定的大小:
$collection = collect(['Taylor', 'Dayle']);
$collection->pad(5, '0');
// ['Taylor', 'Dayle', '0', '0', '0']
負數將從集合的開頭開始填充:
$collection = collect(['Taylor', 'Dayle']);
$collection->pad(-5, '0');
// ['0', '0', '0', 'Taylor', 'Dayle']
partition() {.collection-method}
partition 方法根據真值回呼將集合分割為兩個集合:
$collection = collect([1, 2, 3, 4, 5, 6]);
[$underThree, $overThree] = $collection->partition(function (int $item) {
return $item < 3;
});
$underThree->all();
// [1, 2]
$overThree->all();
// [3, 4, 5, 6]
percentage() {.collection-method}
percentage 方法計算匹配給定回呼的項目百分比:
$collection = collect([1, 2, 3, 4]);
$percentage = $collection->percentage(function (int $item) {
return $item > 2;
});
// 50
pipe() {.collection-method}
pipe 方法將集合傳遞給給定的回呼並返回結果:
$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function (Collection $collection) {
return $collection->sum();
});
// 6
pipeInto() {.collection-method}
pipeInto 方法將集合傳遞給給定類別的構造函數,使用結果建立一個新實例:
use App\Collection;
$collection = collect([1, 2, 3]);
$piped = $collection->pipeInto(Collection::class);
pipeThrough() {.collection-method}
pipeThrough 方法將集合傳遞給給定的管道陣列,返回結果:
use App\Values\Max;
$collection = collect([1, 2, 3]);
$piped = $collection->pipeThrough([
function (Collection $collection) {
return $collection->merge([4, 5]);
},
function (Collection $collection) {
return $collection->filter(function (int $item) {
return $item > 2;
});
},
]);
$piped->all();
// [3, 4, 5]
pluck() {.collection-method}
pluck 方法從集合中檢索一列值:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Adam', 'age' => 15],
]);
$names = $collection->pluck('name');
$names->all();
// ['Taylor', 'Adam']
您可以選擇使用金鑰參數,該參數將用於設定結果集合的金鑰:
$names = $collection->pluck('name', 'age');
$names->all();
// [18 => 'Taylor', 15 => 'Adam']
pop() {.collection-method}
pop 方法從集合中移除並返回最後一個項目:
$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]
prepend() {.collection-method}
prepend 方法將一個項目添加到集合的開頭:
$collection = collect([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]
您可以選擇使用金鑰參數,該參數將用於設定值的金鑰:
$collection = collect(['name' => 'Taylor', 'age' => 18]);
$collection->prepend('Bob', 'name');
$collection->all();
// ['name' => 'Bob', 'age' => 18]
pull() {.collection-method}
pull 方法從集合中移除並返回給定金鑰的項目:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 1]
push() {.collection-method}
push 方法將一個項目追加到集合的結尾:
$collection = collect([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]
put() {.collection-method}
put 方法設定給定金鑰和值:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
random() {.collection-method}
random 方法從集合中返回一個或多個隨機項目:
$collection = collect([1, 2, 3, 4, 5]);
$collection->random();
// 4 // (example output)
$collection->random(3);
// [2, 4, 5] // (example output)
您還可以將 null 作為參數傳遞給 random 方法以返回一個隨機項目的集合:
$collection->random(null)->all();
// [1, 2, 3, 4, 5] // (example output)
range() {.collection-method}
range 方法建立一個包含給定範圍內整數的集合:
$collection = collect()->range(3, 7);
$collection->all();
// [3, 4, 5, 6, 7]
reduce() {.collection-method}
reduce 方法將集合簡化為單一值,將回呼的結果傳遞給下一次迭代:
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function (int $carry, int $item) {
return $carry + $item;
});
// 6
傳遞給回呼的 $carry 值是上一次迭代的結果。您可以透過向 reduce 方法提供第二個參數來指定初始值:
$collection->reduce(function (int $carry, int $item) {
return $carry + $item;
}, 4);
// 10
reduceSpread() {.collection-method}
reduceSpread 方法將集合簡化為單一值,將回呼的結果傳遞給下一次迭代:
$collection = collect([1, 2, 3]);
$reduced = $collection->reduceSpread(function (int $carry, int $value) {
return $carry + $value;
}, 4);
$reduced;
// 10
reject() {.collection-method}
reject 方法使用給定的回呼過濾集合,移除通過真值測試的項目:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->reject(function (int $value, int $key) {
return $value > 2;
});
$filtered->all();
// [1, 2]
reject 方法的相反操作是 filter 方法。
replace() {.collection-method}
replace 方法用另一個陣列或集合中的值替換集合中的值:
$collection = collect([
'Taylor', 'Dayle', 'Matt'
]);
$replaced = $collection->replace([
-1 => 'Taylor', 1 => 'Taylor', 3 => 'Matt'
]);
$replaced->all();
// ['Taylor', 'Taylor', 'Matt']
replaceRecursive() {.collection-method}
replaceRecursive 方法遞歸替換集合中的值:
$collection = collect([
'Taylor',
'[Bengal, Brit',
'Bengal, Brit'
]);
$replaced = $collection->replaceRecursive([
3 => 'Bengal', 4 => 'Brit', 5 => 'Bengal', 6 => 'Brit'
]);
$replaced->all();
// ['Taylor', 'Bengal', 'Brit', 'Bengal', 'Brit']
reverse() {.collection-method}
reverse 方法反轉集合中項目的順序:
$collection = collect([1, 2, 3, 4, 5]);
$reversed = $collection->reverse();
$reversed->all();
// [5, 4, 3, 2, 1]
search() {.collection-method}
search 方法在集合中搜尋給定的值並返回其金鑰。如果找不到值,則返回 false:
$collection = collect([1, 2, 3, 4, 5]);
$collection->search(3);
// 2
$collection->search('foo');
// false
您可以傳遞一個回呼作為第二個參數來自訂搜尋邏輯:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'name' => 'apple',
]);
$collection->search(function (string $key, string $value) {
return $value === 'fruit';
});
// 'type'
select() {.collection-method}
select 方法從集合中選擇給定的金鑰:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Adam', 'age' => 15],
]);
$names = $collection->select('name');
$names->all();
// [['name' => 'Taylor'], ['name' => 'Adam']]
shift() {.collection-method}
shift 方法從集合中移除並返回第一個項目:
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]
shuffle() {.collection-method}
shuffle 方法隨機打亂集合中的項目:
$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] // (example output)
skip() {.collection-method}
skip 方法返回給定數量的項目之後的集合:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$collection = $collection->skip(4);
$collection->all();
// [5, 6, 7, 8, 9, 10]
skipUntil() {.collection-method}
skipUntil 方法跳過項目直到回呼返回 true:
$collection = collect([1, 2, 3, 4]);
$collection = $collection->skipUntil(function (int $item) {
return $item >= 3;
});
$collection->all();
// [3, 4]
skipWhile() {.collection-method}
skipWhile 方法跳過項目直到回呼返回 false:
$collection = collect([1, 2, 3, 4]);
$collection = $collection->skipWhile(function (int $item) {
return $item <= 3;
});
$collection->all();
// [4]
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 方法傳遞一個限制參數:
$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
sliding() {.collection-method}
sliding 方法返回一個集合的集合,其中包含給定大小的滑動窗口:
$collection = collect([1, 2, 3, 4, 5]);
$sliding = $collection->sliding(2);
$sliding->all();
// [[1, 2], [2, 3], [3, 4], [4, 5]]
您可以選擇從給定的偏移量開始:
$collection->sliding(3, 2)->all();
// [[1, 2, 3], [3, 4, 5]]
sole() {.collection-method}
sole 方法返回匹配給定真值測試的第一個項目,如果找到的項目不是一個,則會拋出異常:
$collection = collect([1, 2, 3, 4]);
$collection->sole(function (int $value, int $key) {
return $value > 5;
});
// 會拋出 ItemNotFoundException
some() {.collection-method}
some 方法是 contains 方法的別名。
sort() {.collection-method}
sort 方法按值對集合中的項目進行排序:
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
排序的結果將按照數字金鑰重新索引,就像它已經使用 values 方法過濾過一樣。
如果您的排序標準基於更複雜的比較,您可以將一個回呼傳遞給 sort。請參閱 PHP 的 usort 文件,它將被 sort 方法用於確定排序順序。
sortBy() {.collection-method}
sortBy 方法按給定金鑰對集合中的項目進行排序:
$collection = collect([
['name' => 'John', 'age' => 25],
['name' => 'Jim', 'age' => 30],
['name' => 'Steve', 'age' => 35],
]);
$sorted = $collection->sortBy('age');
$sorted->values()->all();
// [
// ['name' => 'John', 'age' => 25],
// ['name' => 'Jim', 'age' => 30],
// ['name' => 'Steve', 'age' => 35],
// ]
您可以傳遞回呼來定義用於排序的值:
$collection = collect([
'name' => 'Steve',
'age' => 25,
]);
$sorted = $collection->sortBy(function (string $user, int $key) {
return $user['age'];
});
// [
// 'age' => 25,
// 'name' => 'Steve',
// ]
sortByDesc() {.collection-method}
sortByDesc 方法是 sortBy 方法的相反操作,使用降序排序:
$collection = collect([
['name' => 'John', 'age' => 25],
['name' => 'Jim', 'age' => 30],
['name' => 'Steve', 'age' => 35],
]);
$sorted = $collection->sortByDesc('age');
$sorted->values()->all();
// [
// ['name' => 'Steve', 'age' => 35],
// ['name' => 'Jim', 'age' => 30],
// ['name' => 'John', 'age' => 25],
// ]
sortDesc() {.collection-method}
sortDesc 方法使用降序對集合中的項目進行排序:
$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sortDesc();
$sorted->values()->all();
// [5, 4, 3, 2, 1]
sortKeys() {.collection-method}
sortKeys 方法按金鑰對集合中的項目進行排序:
$collection = collect([
'name' => 'Taylor',
'framework' => 'Laravel',
'version' => 10,
]);
$sorted = $collection->sortKeys();
$sorted->all();
// [
// 'framework' => 'Laravel',
// 'name' => 'Taylor',
// 'version' => 10,
// ]
sortKeysDesc() {.collection-method}
sortKeysDesc 方法按金鑰對集合中的項目進行降序排序:
$collection = collect([
'name' => 'Taylor',
'framework' => 'Laravel',
'version' => 10,
]);
$sorted = $collection->sortKeysDesc();
$sorted->all();
// [
// 'version' => 10,
// 'name' => 'Taylor',
// 'framework' => 'Laravel',
// ]
sortKeysUsing() {.collection-method}
sortKeysUsing 方法使用給定的回呼按金鑰對集合中的項目進行排序:
$collection = collect([
'name' => 'Taylor',
'framework' => 'Laravel',
'version' => 10,
]);
$sorted = $collection->sortKeysUsing('strcmp');
$sorted->all();
// [
// 'framework' => 'Laravel',
// 'name' => 'Taylor',
// 'version' => 10,
// ]
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]
您還可以將第四個參數傳遞給 splice 方法,以在從中移除項目子集時在給定偏移量處替換這些項目:
$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]
split() {.collection-method}
split 方法將集合分成給定數量的群組:
$collection = collect([1, 2, 3, 4, 5, 6]);
$splits = $collection->split(2);
$splits->all();
// [[1, 2, 3], [4, 5, 6]]
splitIn() {.collection-method}
splitIn 方法將集合分成給定數量的群組,並且每個群組中的項目數量相同,最後一個群組中不夠的項目除外:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
$splits = $collection->splitIn(3);
$splits->all();
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
sum() {.collection-method}
sum 方法返回集合中所有項目的總和:
collect([1, 2, 3, 4, 5])->sum();
// 15
如果集合包含陣列或物件,您可以指定用於確定總和的金鑰:
$collection = collect([
['name' => 'Car', 'price' => 200],
['name' => 'Bike', 'price' => 150],
]);
$collection->sum('price');
// 350
如果需要,您可以向 sum 方法傳遞一個回呼:
$collection = collect([
['name' => 'Taylor', 'articles' => 162],
['name' => 'Dayle', 'articles' => 46],
]);
$collection->sum(fn (array $user) => $user['articles']);
// 208
take() {.collection-method}
take 方法返回給定數量的項目集合:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
您還可以向 take 方法傳遞一個負數以從集合的結尾開始取得項目:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]
takeUntil() {.collection-method}
takeUntil 方法從集合中取出項目直到回呼返回 true:
$collection = collect([1, 2, 3, 4]);
$collection = $collection->takeUntil(function (int $item) {
return $item >= 3;
});
$collection->all();
// [1, 2]
takeWhile() {.collection-method}
takeWhile 方法從集合中取出項目直到回呼返回 false:
$collection = collect([1, 2, 3, 4]);
$collection = $collection->takeWhile(function (int $item) {
return $item < 3;
});
$collection->all();
// [1, 2]
tap() {.collection-method}
tap 方法將集合傳遞給給定的回呼並返回集合本身。回呼可以對集合執行任何操作而無需修改集合本身:
$collection = collect([1, 2, 3, 4]);
$collection
->tap(function (Collection $collection) {
logger('After first operation:', $collection->all());
})
->push(5)
->tap(function (Collection $collection) {
logger('After second operation:', $collection->all());
})
->pop();
$collection->all();
// [1, 2, 3, 4, 5]
times() {.collection-method}
times 方法建立一個新的集合,並使用給定的回呼結果填充它,該回呼被給定的次數調用:
$collection = collect()->times(3, function (int $number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27]
toArray() {.collection-method}
toArray 方法返回集合所代表的底層陣列:
$collection = collect(['name' => 'Taylor', 'age' => 18]);
$collection->toArray();
// ['name' => 'Taylor', 'age' => 18]
toJson() {.collection-method}
toJson 方法將集合轉換為 JSON 字串:
$collection = collect(['name' => 'Taylor', 'age' => 18]);
$collection->toJson();
// '[{\"name\":\"Taylor\",\"age\":18}]'
toPrettyJson() {.collection-method}
toPrettyJson 方法將集合轉換為格式化良好的 JSON 字串:
$collection = collect(['name' => 'Taylor', 'age' => 18]);
$collection->toPrettyJson();
// '[{\n \"name\": \"Taylor\",\n \"age\": 18\n}]'
transform() {.collection-method}
transform 方法使用給定的回呼遍歷集合中的項目,並使用回呼的結果替換每個項目。此方法在映射或修改集合中的項目時非常有用:
$collection = collect([1, 2, 3, 4, 5]);
$collection = $collection->transform(function (int $item, int $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
[!WARNING] 如果您想保留原始集合,請使用 map 方法。
undot() {.collection-method}
undot 方法使用「點」語法展平一維陣列到多維陣列中:
$person = collect([
'name.foo.name' => 'Taylor',
'name.foo.email' => '[email protected]',
]);
$undotted = $person->undot();
$undotted->toArray();
// ['name' => ['foo' => ['name' => 'Taylor', 'email' => '[email protected]']]]
union() {.collection-method}
union 方法將給定的陣列或集合附加到另一個集合中,同時保留原始金鑰。如果給定的陣列或集合中的金鑰與原始集合中的金鑰衝突,則原始集合中的值將保留:
$collection = collect([1 => 100, 2 => 200]);
$union = $collection->union([3 => 300, 1 => 100]);
$union->all();
// [1 => 100, 2 => 200, 3 => 300]
unique() {.collection-method}
unique 方法返回集合中的所有唯一項目。此方法保留原始集合的金鑰:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
如果集合包含陣列或物件,您可以指定用於確定唯一性的金鑰:
$employees = collect([
['email' => '[email protected]', 'name' => 'John Gamez', 'age' => 45],
['email' => '[email protected]', 'name' => 'Dave', 'age' => 45],
['email' => '[email protected]', 'name' => 'Jane Doe', 'age' => 45],
]);
$uniqueEmployees = $employees->unique('email');
$uniqueEmployees->values()->all();
// [
// ['email' => '[email protected]', 'name' => 'John Gamez', 'age' => 45],
// ['email' => '[email protected]', 'name' => 'Dave', 'age' => 45],
// ]
unique 方法在比較值時使用「鬆散」比較,這意味著具有整數值的字串將被認為等於相同值的整數。使用 uniqueStrict 方法使用「嚴格」比較進行篩選。
uniqueStrict() {.collection-method}
此方法具有與 unique 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。
[!NOTE] 使用 Eloquent 集合時,此方法的行為會被修改。
unless() {.collection-method}
unless 方法在給定的布林條件為 false 時對集合執行給定的回呼:
$collection = collect([1, 2, 3]);
$collection->unless(false, function (Collection $collection) {
return $collection->push(4);
});
// [1, 2, 3, 4]
如果未傳遞回呼,unless 方法將在布林條件為 false 時返回給定的值:
$collection = collect([1, 2, 3]);
$collection = $collection->unless(false);
// [1, 2, 3, 4]
unlessEmpty() {.collection-method}
unlessEmpty 方法是 whenNotEmpty 方法的別名。
unlessNotEmpty() {.collection-method}
unlessNotEmpty 方法是 whenEmpty 方法的別名。
unwrap() {.collection-method}
unwrap 方法從集合的開頭和結尾移除給定的值:
$collection = collect('-Laravel-');
$collection = $collection->unwrap('-');
$collection->all();
// ['Laravel']
value() {.collection-method}
value 方法返回給定金鑰的值。如果金鑰不存在,則返回預設值:
$collection = collect([1, 2, 3, 4, 5]);
$collection->value(3);
// 4
values() {.collection-method}
values 方法重新索引集合中的項目,按數字順序分配從零開始的新金鑰:
$collection = collect([
10 => ['one', 10],
1 => ['two', 20],
200 => ['three', 30],
]);
$values = $collection->values();
$values->all();
// [
// 0 => ['one', 10],
// 1 => ['two', 20],
// 2 => ['three', 30],
// ]
when() {.collection-method}
when 方法在給定的布林條件為 true 時對集合執行給定的回呼:
$collection = collect([1, 2, 3]);
$collection->when(true, function (Collection $collection, int $value) {
return $collection->push(4);
});
// [1, 2, 3, 4]
如果未傳遞回呼,when 方法將在布林條件為 true 時返回給定的值:
$collection = collect([1, 2, 3]);
$collection = $collection->when(true);
// [1, 2, 3, 4]
whenEmpty() {.collection-method}
whenEmpty 方法在集合為空時對集合執行給定的回呼:
$collection = collect([]);
$collection->whenEmpty(function (Collection $collection) {
return $collection->push('Taylor');
});
// ['Taylor']
如果未傳遞回呼,whenEmpty 方法將在集合為空時返回一個新的空集合:
$collection = collect([]);
$collection = $collection->whenEmpty();
// new Collection([])
whenNotEmpty() {.collection-method}
whenNotEmpty 方法在集合不為空時對集合執行給定的回呼:
$collection = collect([1, 2, 3]);
$collection->whenNotEmpty(function (Collection $collection, int $value) {
return $collection->push(4);
});
// [1, 2, 3, 4]
如果未傳遞回呼,whenNotEmpty 方法將在集合不為空時返回給定的值:
$collection = collect([1, 2, 3]);
$collection = $collection->whenNotEmpty();
// [1, 2, 3, 4]
where() {.collection-method}
where 方法使用給定的金鑰/值對過濾集合:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => 15],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->where('age', 16);
$filtered->all();
// [
// ['name' => 'Matt', 'age' => 16],
// ]
您可以使用「鬆散」比較,這是預設的,也可以使用「嚴格」比較:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => '15'],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->where('age', 16);
// [0 => ['name' => 'Dayle', 'age' => '15']]
$filtered = $collection->where('age', 16, strict: true);
// [2 => ['name' => 'Matt', 'age' => 16]]
whereStrict() {.collection-method}
此方法具有與 where 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。
whereBetween() {.collection-method}
whereBetween 方法使用給定的範圍過濾集合:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => 15],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->whereBetween('age', [15, 17]);
$filtered->all();
// [
// ['name' => 'Dayle', 'age' => 15],
// ['name' => 'Matt', 'age' => 16],
// ]
whereIn() {.collection-method}
whereIn 方法使用給定的值過濾集合:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => 15],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->whereIn('age', [16, 15]);
$filtered->all();
// [
// ['name' => 'Dayle', 'age' => 15],
// ['name' => 'Matt', 'age' => 16],
// ]
您可以使用「鬆散」比較,這是預設的,也可以使用「嚴格」比較:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => '15'],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->whereIn('age', [15, 16]);
// [0 => ['name' => 'Dayle', 'age' => '15']]
$filtered = $collection->whereIn('age', [15, 16], strict: true);
// [2 => ['name' => 'Matt', 'age' => 16]]
whereInStrict() {.collection-method}
此方法具有與 whereIn 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。
whereInstanceOf() {.collection-method}
whereInstanceOf 方法過濾集合中給定類型的項目:
use App\Models\User;
$users = $collection->whereInstanceOf(User::class);
whereNotBetween() {.collection-method}
whereNotBetween 方法使用不屬於給定範圍的值過濾集合:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => 15],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->whereNotBetween('age', [15, 17]);
$filtered->all();
// [
// ['name' => 'Taylor', 'age' => 18],
// ]
whereNotIn() {.collection-method}
whereNotIn 方法使用不屬於給定陣列的值過濾集合:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => 15],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->whereNotIn('age', [15, 16]);
$filtered->all();
// [
// ['name' => 'Taylor', 'age' => 18],
// ]
您可以使用「鬆散」比較,這是預設的,也可以使用「嚴格」比較:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => '15'],
['name' => 'Matt', 'age' => 16],
]);
$filtered = $collection->whereNotIn('age', [15, 16]);
// [2 => ['name' => 'Matt', 'age' => 16]]
$filtered = $collection->whereNotIn('age', [15, 16], strict: true);
// [0 => ['name' => 'Taylor', 'age' => 18], [1 => ['name' => 'Dayle', 'age' => '15']]
whereNotInStrict() {.collection-method}
此方法具有與 whereNotIn 方法相同的簽名;但是,所有值都使用「嚴格」比較進行比較。
whereNotNull() {.collection-method}
whereNotNull 方法過濾具有給定金鑰且值不為 null 的項目:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => null],
]);
$filtered = $collection->whereNotNull('age');
$filtered->all();
// [
// ['name' => 'Taylor', 'age' => 18],
// ]
whereNull() {.collection-method}
whereNull 方法過濾具有給定金鑰且值為 null 的項目:
$collection = collect([
['name' => 'Taylor', 'age' => 18],
['name' => 'Dayle', 'age' => null],
]);
$filtered = $collection->whereNull('age');
$filtered->all();
// [
// ['name' => 'Dayle', 'age' => null],
// ]
wrap() {.collection-method}
wrap 方法將給定的值包裝在一個集合中:
use Illuminate\Support\Collection;
$collection = Collection::wrap('Taylor');
$collection->all();
// ['Taylor']
如果給定的值已經是一個集合,wrap 方法將不會將其包裝在集合中:
use Illuminate\Support\Collection;
$original = collect([1, 2, 3]);
$wrapped = Collection::wrap($original);
$original === $wrapped;
// true
zip() {.collection-method}
zip 方法將給定的陣列或集合的值與原始集合的值合併在一起:
$collection = collect(['Taylor', 'Dayle']);
$zipped = $collection->zip(['male', 'male', 'female']);
$zipped->all();
// [['Taylor', 'male'], ['Dayle', 'male']]
高階消息
高階消息提供了方便的方式來在集合中執行常見的操作,而無需編寫閉包。高階消息可用於 filter、reject、forEach、map、flatMap、filter、first、last、forPage、reject、sort、sortBy、sortByDesc、sum、count、avg、max、min 和 median:
use App\Models\User;
$users = User::where('orders', '>=', 1)->get();
$users->filter->isAdmin();
這與以下內容相同:
$users->filter(function (User $user) {
return $user->isAdmin();
});
您可以使用「點」語法來存取巢狀物件上的屬性:
$orders = User::with('books')->get();
$orders->filter->books->isEmpty();
延遲集合
簡介
延遲集合允許您以程式碼的方式處理可能無法放入記憶體的結果。例如,eloquent cursor 方法使用延遲集合,從而減少對資料庫的記憶體使用量。延遲集合提供的大多數方法與其不可變的集合對應物相同;然而,延遲集合的內部迭代器不會一直被快取到記憶體中。這允許在使用數十億個項目的集合時,在記憶體佔用量上實現巨大的效率提升:
use Illuminate\Support\Collection;
$collection = collect(range(1, 1000000));
$collection->each(function (int $number) {
echo $number;
});
// 1234567891011121314151617181920212223...
相反,每個項目的延遲集合版本將在項目的值進入記憶體之前生成一個項目的值:
$collection = LazyCollection::range(1, 1000000);
$collection->each(function (int $number) {
echo $number;
});
// 1234567891011121314151617181920212223...
建立延遲集合
延遲集合可以從 LazyCollection 類別直接建立:
use Illuminate\Support\LazyCollection;
$lazyCollection = LazyCollection::range(1, 1000000);
$lazyCollection->each(function (int $number) {
echo $number;
});
// 1234567891011121314151617181920212223...
或者,您可以從集合或陣列建立延遲集合:
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
$collection = collect([1, 2, 3, 4, 5]);
$lazyCollection = $collection->lazy();
$lazyCollection::class;
// 'Illuminate\Support\LazyCollection'
$lazyCollection->toArray();
// [1, 2, 3, 4, 5]
您還可以從陣列建立延遲集合:
use Illuminate\Support\LazyCollection;
$lazyCollection = LazyCollection::times(10, function (int $number) {
return $number * 9;
});
$lazyCollection->toArray();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
The Enumerable Contract
延遲集合實現了 Enumerable 介面,這意味著延遲集合具有與其不可變的集合對應物相同的所有方法。然而,由於延遲集合不是可索引的,因此不支援陣列存取和修改方法。
延遲集合方法
LazyCollection 類別提供了多種用於延遲集合的方法。以下列出了其中的一些:
remember() {.collection-method .first-collection-method}
remember 方法將延遲集合的值快取在記憶體中,以便它們在後續迭代期間不會重新生成:
use Illuminate\Support\LazyCollection;
$lazyCollection = LazyCollection::times(10, function (int $number) {
return $number * 9;
})->remember();
$lazyCollection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
take() {.collection-method}
take 方法返回給定數量的項目集合:
use Illuminate\Support\LazyCollection;
$lazyCollection = LazyCollection::range(1, 10);
$lazyCollection->take(5)->all();
// [1, 2, 3, 4, 5]
until() {.collection-method}
until 方法從延遲集合中取出項目直到回呼返回 true:
use Illuminate\Support\LazyCollection;
$lazyCollection = LazyCollection::range(1, 10);
$lazyCollection->until(fn (int $number) => $number > 5)->all();
// [1, 2, 3, 4, 5]
peek() {.collection-method}
peek 方法返回延遲集合中將要處理的下一個項目,而不實際從集合中移除它:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3])->lazy();
$lazyCollection->peek()->all();
// [1]
collect() {.collection-method}
collect 方法將延遲集合快取在記憶體中,並將其作為一個常規的 Collection 實例返回:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3])->lazy();
$lazyCollection->collect()->toArray();
// [1, 2, 3]
contains() {.collection-method}
contains 方法驗證延遲集合是否包含給定的值:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->contains(2);
// true
dump() {.collection-method}
dump 方法轉儲延遲集合中的項目:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->dump()->toArray();
// 1
// 2
// 3
// 4
// 5
dd() {.collection-method}
dd 方法轉儲延遲集合中的項目並終止腳本的執行:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->dd();
filter() {.collection-method}
filter 方法使用給定的回呼過濾延遲集合:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection = $lazyCollection->filter(function (int $value) {
return $value > 2;
});
$lazyCollection->all();
// [3, 4, 5]
first() {.collection-method}
first 方法返回延遲集合的第一個元素,如果沒有元素,則返回 null:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->first();
// 1
forEach() {.collection-method}
forEach 方法遍歷延遲集合中的項目,將每個項目傳遞給回呼:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->forEach(function (int $value, int $key) {
echo "{$key}: {$value}\n";
});
// 0: 1
// 1: 2
// 2: 3
// 3: 4
// 4: 5
forPage() {.collection-method}
forPage 方法返回給定頁碼的項目集合:
use Illuminate\Support\LazyCollection;
$lazyCollection = LazyCollection::range(1, 10)->forPage(2, 3);
$lazyCollection->all();
// [4, 5, 6]
forget() {.collection-method}
forget 方法從延遲集合中移除給定金鑰的項目:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([
'name' => 'Taylor',
'name' => 'Dayle',
'name' => 'Matt'
])->lazy();
$lazyCollection->forget('name');
$lazyCollection->all();
// [1, 2, 3]
implode() {.collection-method}
implode 方法使用字串連接延遲集合中的項目:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect(['Taylor', 'Dayle', 'Matt'])->lazy();
$lazyCollection->implode(', ');
// "Taylor, Dayle, Matt"
map() {.collection-method}
map 方法遍歷延遲集合中的項目,將每個項目傳遞給回呼,然後使用結果填充一個新的實例:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection = $lazyCollection->map(function (int $number) {
return $number * 9;
});
$lazyCollection->toArray();
// [9, 18, 27, 36, 45]
only() {.collection-method}
only 方法返回具有給定金鑰的項目。此方法的相反操作是 except 方法:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([
'name' => 'Taylor',
'name' => 'Dayle',
'name' => 'Matt'
])->lazy();
$lazyCollection->only(['name', 'price']);
$lazyCollection->all();
// ['Taylor', 'Dayle', 'Matt']
except() {.collection-method}
except 方法返回不具有給定金鑰的所有項目。此方法的相反操作是 only 方法:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([
'name' => 'Taylor',
'name' => 'Dayle',
'name' => 'Matt'
])->lazy();
$lazyCollection->except(['price', 'discount']);
$lazyCollection->all();
// ['Taylor', 'Dayle', 'Matt']
reduce() {.collection-method}
reduce 方法將延遲集合簡化為單一值,將回呼的結果傳遞給下一次迭代:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$reduced = $lazyCollection->reduce(function (int $carry, int $number) {
return $carry + $number;
});
// 15
sort() {.collection-method}
sort 方法按值對延遲集合中的項目進行排序:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([5, 3, 1, 2, 4])->lazy();
$sorted = $lazyCollection->sort();
$sorted->all();
// [1, 2, 3, 4, 5]
sum() {.collection-method}
sum 方法返回延遲集合中所有項目的總和:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->sum();
// 15
toArray() {.collection-method}
toArray 方法將延遲集合快取在記憶體中並返回底層陣列:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->toArray();
// [1, 2, 3, 4, 5]
toJson() {.collection-method}
toJson 方法將延遲集合轉換為 JSON 字串:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3, 4, 5])->lazy();
$lazyCollection->toJson();
// '[1,2,3,4,5]'
zip() {.collection-method}
zip 方法將給定的陣列或集合的值與原始延遲集合的值合併在一起:
use Illuminate\Support\LazyCollection;
$lazyCollection = collect([1, 2, 3])->lazy();
$lazyCollection->zip([100, 200, 300])->all();
// [[1, 100], [2, 200], [3, 300]]