該存儲庫包含一些有用的集合巨集。
Spatie 是一家位於比利時安特衛普的網頁設計公司。您可以在我們的網站上找到所有開源專案的概述。
我們投入了大量資源來創建一流的開源套件。您可以透過購買我們的一款付費產品來支持我們。
我們非常感謝您從家鄉寄給我們一張明信片,並註明您正在使用我們的哪種套餐。您可以在我們的聯絡頁面上找到我們的地址。我們在虛擬明信片牆上發布所有收到的明信片。
您可以透過composer拉入包:
composer require spatie/laravel-collection-macros
該包將自動註冊。
after
at
second
third
fourth
fifth
sixth
seventh
eighth
ninth
tenth
getNth
before
catch
chunkBy
collectBy
containsAny
containsAll
eachCons
extract
filterMap
firstOrFail
firstOrPush
fromPairs
getCaseInsensitive
glob
groupByModel
hasCaseInsensitive
head
if
ifAny
ifEmpty
insertAfter
insertAfterKey
insertAt
insertBefore
insertBeforeKey
none
paginate
path
pluckMany
pluckManyValues
pluckToArray
prioritize
recursive
rotate
sectionBy
simplePaginate
sliceBefore
tail
try
toPairs
transpose
validate
weightedRandom
withSize
after
從集合中取得下一個項目。
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 2 ;
$ currentItem = $ collection -> after ( $ currentItem ); // return 3;
$ collection -> after ( $ currentItem ); // return null;
$ currentItem = $ collection -> after ( function ( $ item ) {
return $ item > 1 ;
}); // return 3;
您也可以傳遞第二個參數作為後備。
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 3 ;
$ collection -> after ( $ currentItem , $ collection -> first ()); // return 1;
at
檢索索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 ]);
$ data -> at ( 0 ); // 1
$ data -> at ( 1 ); // 2
$ data -> at (- 1 ); // 3
second
檢索第二個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> second (); // 2
third
檢索第三個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> third (); // 3
fourth
檢索第四個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fourth (); // 4
fifth
檢索第五個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fifth (); // 5
sixth
檢索第六個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> sixth (); // 6
seventh
檢索第七個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> seventh (); // 7
eighth
檢索第八個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> eighth (); // 8
ninth
檢索第九個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> ninth (); // 9
tenth
檢索第十個索引處的項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> tenth (); // 10
getNth
檢索第 n 個項目。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ]);
$ data -> getNth ( 11 ); // 11
before
從集合中取得上一個項目。
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 2 ;
$ currentItem = $ collection -> before ( $ currentItem ); // return 1;
$ collection -> before ( $ currentItem ); // return null;
$ currentItem = $ collection -> before ( function ( $ item ) {
return $ item > 2 ;
}); // return 2;
您也可以傳遞第二個參數作為後備。
$ collection = collect ([ 1 , 2 , 3 ]);
$ currentItem = 1 ;
$ collection -> before ( $ currentItem , $ collection -> last ()); // return 3;
catch
請參閱Try
chunkBy
只要給定的回調為 true,就會將集合中的值分成組。如果可選參數$preserveKeys
為true
被傳遞,它將保留原始金鑰。
collect ([ ' A ' , ' A ' , ' B ' , ' A ' ])-> chunkBy ( function ( $ item ) {
return $ item == ' A ' ;
}); // return Collection([['A', 'A'],['B'], ['A']])
collectBy
在給定的鑰匙處獲取物品並收集它。
$ collection = collect ([
' foo ' => [ 1 , 2 , 3 ],
' bar ' => [ 4 , 5 , 6 ],
]);
$ collection -> collectBy ( ' foo ' ); // Collection([1, 2, 3])
您也可以傳遞第二個參數作為後備。
$ collection = collect ([
' foo ' => [ 1 , 2 , 3 ],
' bar ' => [ 4 , 5 , 6 ],
]);
$ collection -> collectBy ( ' baz ' , [ ' Nope ' ]); // Collection(['Nope'])
containsAny
如果集合中存在一個或多個給定值,則傳回true
。
$ collection = collect ([ ' a ' , ' b ' , ' c ' ]);
$ collection -> containsAny ([ ' b ' , ' c ' , ' d ' ]); // returns true
$ collection -> containsAny ([ ' c ' , ' d ' , ' e ' ]); // returns true
$ collection -> containsAny ([ ' d ' , ' e ' , ' f ' ]); // returns false
$ collection -> containsAny ([]); // returns false
containsAll
如果集合中存在所有給定值,則傳回true
。
$ collection = collect ([ ' a ' , ' b ' , ' c ' ]);
$ collection -> containsAll ([ ' b ' , ' c ' ,]); // returns true
$ collection -> containsAll ([ ' c ' , ' d ' ]); // returns false
$ collection -> containsAll ([ ' d ' , ' e ' ]); // returns false
$ collection -> containsAll ([]); // returns true
eachCons
從給定的區塊大小中取得集合中的以下連續鄰居。如果可選參數$preserveKeys
為true
被傳遞,它將保留原始金鑰。
collect ([ 1 , 2 , 3 , 4 ])-> eachCons ( 2 ); // return collect([[1, 2], [2, 3], [3, 4]])
extract
從集合中提取密鑰。這與only
非常相似,但有兩個關鍵區別:
extract
傳回值數組,而不是關聯數組null
填充該值而不是省略它extract
在使用 PHP 7.1 Short list()
語法時非常有用。
[ $ name , $ role ] = collect ( $ user )-> extract ( ' name ' , ' role.name ' );
filterMap
一次性映射一個集合並刪除虛假值。
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 ])-> filterMap ( function ( $ number ) {
$ quotient = $ number / 3 ;
return is_integer ( $ quotient ) ? $ quotient : null ;
});
$ collection -> toArray (); // returns [1, 2]
firstOrFail
獲取第一個項目。如果找不到該項目,則拋出SpatieCollectionMacrosExceptionsCollectionItemNotFound
。
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 ])-> firstOrFail ();
$ collection -> toArray (); // returns [1]
collect ([])-> firstOrFail (); // throws SpatieCollectionMacrosExceptionsCollectionItemNotFound
firstOrPush
使用作為第一個參數給出的可調用項檢索第一個項目。如果不存在值,則將第二個參數的值推入集合中。您可以傳遞可呼叫物件作為第二個參數。
在處理快取的類別屬性時,此方法非常有用,您希望將從 API 檢索的值或計算量大的函數儲存在集合中以便多次使用。
$ collection = collect ([ 1 , 2 , 3 ])-> firstOrPush ( fn ( $ item ) => $ item === 4 , 4 );
$ collection -> toArray (); // returns [1, 2, 3, 4]
有時,您需要指定要推送到的目標集合。您可以將其作為第三個參數傳遞。
$ collection = collect ([ 1 , 2 , 3 ]);
$ collection -> filter ()-> firstOrPush ( fn ( $ item ) => $ item === 4 , 4 , $ collection );
$ collection -> toArray (); // returns [1, 2, 3, 4]
fromPairs
將集合轉換為關聯數組形式的集合項目。
$ collection = collect ([[ ' a ' , ' b ' ], [ ' c ' , ' d ' ], [ ' e ' , ' f ' ]])-> fromPairs ();
$ collection -> toArray (); // returns ['a' => 'b', 'c' => 'd', 'e' => 'f']
getCaseInsensitive
取得給定鍵的值。
如果鍵是字串,我們將使用不區分大小寫的比較來搜尋鍵。
$ collection = collect ([
' foo ' => ' bar ' ,
]);
$ collection -> getCaseInsensitive ( ' Foo ' ); // returns 'bar';
glob
傳回glob()
結果的集合。
Collection:: glob ( ' config/*.php ' );
groupByModel
與groupBy
類似,但透過 Eloquent 模型對集合進行分組。由於鍵是一個物件而不是整數或字串,因此結果被分成單獨的陣列。
$ posts -> groupByModel ( ' category ' );
// [
// [$categoryA, [/*...$posts*/]],
// [$categoryB, [/*...$posts*/]],
// ];
完整簽章: groupByModel($callback, $preserveKeys, $modelKey, $itemsKey)
hasCaseInsensitive
確定集合是否包含具有給定名稱的鍵。
如果 $key 是字串,我們將使用不區分大小寫的比較來搜尋鍵。
$ collection = collect ([
' foo ' => ' bar ' ,
]);
$ collection -> hasCaseInsensitive ( ' Foo ' ); // returns true;
head
從集合中檢索第一項。
$ collection = collect ([ 1 , 2 , 3 ]);
$ collection -> head (); // return 1
$ collection = collect ([]);
$ collection -> head (); // return null
if
if
宏可以幫助分支集合鏈。這是該巨集的簽章:
if (mixed $ if , mixed $ then = null , mixed $ else = null ): mixed
$if
、 $then
和$else
可以是任何類型。如果將閉包傳遞給任何這些參數,則將執行該閉包並且巨集將使用其結果。
當$if
傳回真值時,則傳回$then
,否則傳回$else
。
以下是一些範例:
collect ()-> if ( true , then: true , else: false ); // returns true
collect ()-> if ( false , then: true , else: false ); // returns false
當閉包傳遞給$if
、 $then
或$else
時,整個集合將作為參數傳遞給該閉包。
// the `then` closure will be executed
// the first element of the returned collection now contains "THIS IS THE VALUE"
$ collection = collect ([ ' this is a value ' ])
-> if (
fn ( Collection $ collection ) => $ collection -> contains ( ' this is a value ' ),
then: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => strtoupper ( $ item )),
else: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => Str:: kebab ( $ item ))
);
// the `else` closure will be executed
// the first element of the returned collection now contains "this-is-another-value"
$ collection = collect ([ ' this is another value ' ])
-> if (
fn ( Collection $ collection ) => $ collection -> contains ( ' this is a value ' ),
then: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => strtoupper ( $ item )),
else: fn ( Collection $ collection ) => $ collection -> map ( fn ( string $ item ) => Str:: kebab ( $ item ))
);
ifAny
如果集合不為空,則執行傳遞的可呼叫物件。整個收藏品將被退回。
collect ()-> ifAny ( function ( Collection $ collection ) { // empty collection so this won't get called
echo ' Hello ' ;
});
collect ([ 1 , 2 , 3 ])-> ifAny ( function ( Collection $ collection ) { // non-empty collection so this will get called
echo ' Hello ' ;
});
ifEmpty
如果集合為空,則執行傳遞的可呼叫物件。整個收藏品將被退回。
collect ()-> ifEmpty ( function ( Collection $ collection ) { // empty collection so this will called
echo ' Hello ' ;
});
collect ([ 1 , 2 , 3 ])-> ifEmpty ( function ( Collection $ collection ) { // non-empty collection so this won't get called
echo ' Hello ' ;
});
insertAfter
在給定項目第一次出現後插入一個項目並傳回更新後的 Collection 實例。可以選擇提供密鑰。
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertAfter ( ' zero ' , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertAfter ( 0 , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
insertAfterKey
在給定鍵後插入一個項目並傳回更新的 Collection 實例。可以選擇提供新項目的密鑰。
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertAfterKey ( 0 , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertAfterKey ( ' zero ' , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
insertAt
在給定索引處插入一個項目並傳回更新後的 Collection 實例。可以選擇提供密鑰。
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertAt ( 1 , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertAt ( 1 , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
insertBefore
在給定專案第一次出現之前插入一個項目並傳回更新後的 Collection 實例。可以選擇提供密鑰。
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertBefore ( ' two ' , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertBefore ( 2 , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
insertBeforeKey
在給定鍵之前插入一個項目並傳回更新的 Collection 實例。可以選擇提供新項目的密鑰。
collect ([ ' zero ' , ' two ' , ' three ' ])-> insertBeforeKey ( 1 , ' one ' );
// Collection contains ['zero', 'one', 'two', 'three']
collect ([ ' zero ' => 0 , ' two ' => 2 , ' three ' => 3 ]-> insertBeforeKey ( ' two ' , 5 , ' five ' );
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]
none
檢查集合是否不包含任何給定項目、鍵值對或通過真值測試。此函數接受與contains
集合方法相同的參數。
collect ([ ' foo ' ])-> none ( ' bar ' ); // returns true
collect ([ ' foo ' ])-> none ( ' foo ' ); // returns false
collect ([[ ' name ' => ' foo ' ]])-> none ( ' name ' , ' bar ' ); // returns true
collect ([[ ' name ' => ' foo ' ]])-> none ( ' name ' , ' foo ' ); // returns false
collect ([ ' name ' => ' foo ' ])-> none ( function ( $ key , $ value ) {
return $ key === ' name ' && $ value === ' bar ' ;
}); // returns true
paginate
為集合中的項目建立LengthAwarePaginator
實例。
collect ( $ posts )-> paginate ( 5 );
這對$posts
的內容進行分頁,每頁 5 個項目。 paginate
接受相當多的選項,請造訪 Laravel 文件以獲得深入的指南。
paginate(int $perPage = 15, string $pageName = 'page', ?int $page = null, ?int $total = null, array $options = [])
path
使用“點”表示法從具有多維資料的集合中傳回項目。運作方式與本機 Collection 的pull
方法相同,但不會從集合中刪除項目。
$ collection = new Collection ([
' foo ' => [
' bar ' => [
' baz ' => ' value ' ,
]
]
]);
$ collection -> path ( ' foo.bar.baz ' ) // 'value'
pluckMany
傳回僅包含指定鍵的集合。
$ collection = collect ([
[ ' a ' => 1 , ' b ' => 10 , ' c ' => 100 ],
[ ' a ' => 2 , ' b ' => 20 , ' c ' => 200 ],
]);
$ collection -> pluckMany ([ ' a ' , ' b ' ]);
// returns
// collect([
// ['a' => 1, 'b' => 10],
// ['a' => 2, 'b' => 20],
// ]);
pluckManyValues
傳回僅包含指定鍵值的集合。
$ collection = collect ([
[ ' a ' => 1 , ' b ' => 10 , ' c ' => 100 ],
[ ' a ' => 2 , ' b ' => 20 , ' c ' => 200 ],
]);
$ collection -> pluckMany ([ ' a ' , ' b ' ]);
// returns
// collect([
// [1, 10],
// [2, 20],
// ]);
pluckToArray
傳回給定鍵的值數組。
$ collection = collect ([
[ ' a ' => 1 , ' b ' => 10 ],
[ ' a ' => 2 , ' b ' => 20 ],
[ ' a ' => 3 , ' b ' => 30 ]
]);
$ collection -> pluckToArray ( ' a ' ); // returns [1, 2, 3]
prioritize
將元素移到集合的開頭。
$ collection = collect ([
[ ' id ' => 1 ],
[ ' id ' => 2 ],
[ ' id ' => 3 ],
]);
$ collection
-> prioritize ( function ( array $ item ) {
return $ item [ ' id ' ] === 2 ;
})
-> pluck ( ' id ' )
-> toArray (); // returns [2, 1, 3]
recursive
使用遞歸將數組及其子數組轉換為集合。
collect ([
' item ' => [
' children ' => []
]
])-> recursive ();
// subsequent arrays are now collections
在某些情況下,您可能不想將所有子項目都變成一個集合。您可以透過向遞歸方法提供數字來僅轉換為特定深度。
collect ([
' item ' => [
' children ' => [
' one ' => [ 1 ],
' two ' => [ 2 ]
]
]
])-> recursive ( 1 ); // Collection(['item' => Collection(['children' => ['one' => [1], 'two' => [2]]])])
當您知道在一定深度上它是不必要的或它可能會破壞您的程式碼時,這會很有用。
collect ([
' item ' => [
' children ' => [
' one ' => [ 1 ],
' two ' => [ 2 ]
]
]
])
-> recursive ( 1 )
-> map ( function ( $ item ) {
return $ item -> map ( function ( $ children ) {
return $ children -> mapInto (Model::class);
});
}); // Collection(['item' => Collection(['children' => ['one' => Model(), 'two' => Model()]])])
// If we do not pass a max depth we will get the error "Argument #1 ($attributes) must be of type array"
rotate
以給定的偏移旋轉集合中的項目
$ collection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 ]);
$ rotate = $ collection -> rotate ( 1 );
$ rotate -> toArray ();
// [2, 3, 4, 5, 6, 1]
sectionBy
將集合拆分為按給定鍵分組的部分。與groupBy
類似,但尊重集合中項目的順序並重複使用現有鍵。
$ collection = collect ([
[ ' name ' => ' Lesson 1 ' , ' module ' => ' Basics ' ],
[ ' name ' => ' Lesson 2 ' , ' module ' => ' Basics ' ],
[ ' name ' => ' Lesson 3 ' , ' module ' => ' Advanced ' ],
[ ' name ' => ' Lesson 4 ' , ' module ' => ' Advanced ' ],
[ ' name ' => ' Lesson 5 ' , ' module ' => ' Basics ' ],
]);
$ collection -> sectionBy ( ' module ' );
// [
// ['Basics', [
// ['name' => 'Lesson 1', 'module' => 'Basics'],
// ['name' => 'Lesson 2', 'module' => 'Basics'],
// ]],
// ['Advanced', [
// ['name' => 'Lesson 3', 'module' => 'Advanced'],
// ['name' => 'Lesson 4', 'module' => 'Advanced'],
// ]],
// ['Basics', [
// ['name' => 'Lesson 5', 'module' => 'Basics'],
// ]],
// ];
完整簽名: sectionBy($callback, $preserveKeys, $sectionKey, $itemsKey)
simplePaginate
為集合中的項目建立一個Paginator
實例。
collect ( $ posts )-> simplePaginate ( 5 );
這對$posts
的內容進行分頁,每頁 5 個項目。 simplePaginate
接受相當多的選項,請前往 Laravel 文件以取得深入指南。
simplePaginate(int $perPage = 15, string $pageName = 'page', ?int $page = null, ?int $total = null, array $options = [])
有關分頁的深入指南,請查看 Laravel 文件。
sliceBefore
在給定的回調為 true 之前,將值從集合中切出。如果可選參數$preserveKeys
為true
被傳遞,它將保留原始金鑰。
collect ([ 20 , 51 , 10 , 50 , 66 ])-> sliceBefore ( function ( $ item ) {
return $ item > 50 ;
}); // return collect([[20],[51, 10, 50], [66])
tail
從集合中提取尾部。所以除了第一個元素之外的所有內容。它是slice(1)->values()
的簡寫,但仍然非常方便。如果可選參數$preserveKeys
作為true
被傳遞,它將保留鍵並回退到slice(1)
。
collect ([ 1 , 2 , 3 ])-> tail (); // return collect([2, 3])
toPairs
將集合轉換為包含對的陣列。
$ collection = collect ([ ' a ' => ' b ' , ' c ' => ' d ' , ' e ' => ' f ' ])-> toPairs ();
$ collection -> toArray (); // returns ['a', 'b'], ['c', 'd'], ['e', 'f']
transpose
轉置的目標是旋轉多維數組,將行變成列,將列變成行。
collect ([
[ ' Jane ' , ' Bob ' , ' Mary ' ],
[ ' [email protected] ' , ' [email protected] ' , ' [email protected] ' ],
[ ' Doctor ' , ' Plumber ' , ' Dentist ' ],
])-> transpose ()-> toArray ();
// [
// ['Jane', '[email protected]', 'Doctor'],
// ['Bob', '[email protected]', 'Plumber'],
// ['Mary', '[email protected]', 'Dentist'],
// ]
try
如果try
和catch
之間的任何方法拋出異常,則可以在catch
中處理該異常。
collect ([ ' a ' , ' b ' , ' c ' , 1 , 2 , 3 ])
-> try ()
-> map ( fn ( $ letter ) => strtoupper ( $ letter ))
-> each ( function () {
throw new Exception ( ' Explosions in the sky ' );
})
-> catch ( function ( Exception $ exception ) {
// handle exception here
})
-> map ( function () {
// further operations can be done, if the exception wasn't rethrow in the `catch`
});
雖然為了熟悉 PHP,這些方法被命名為try
/ catch
,但集合本身的行為更像是資料庫事務。因此,當拋出異常時,將傳回原始集合(在 try 之前)。
您可以透過在處理程序中新增第二個參數來存取 catch 中的集合。您也可以透過傳回值來操作 catch 中的集合。
$ collection = collect ([ ' a ' , ' b ' , ' c ' , 1 , 2 , 3 ])
-> try ()
-> map ( function ( $ item ) {
throw new Exception ();
})
-> catch ( function ( Exception $ exception , $ collection ) {
return collect ([ ' d ' , ' e ' , ' f ' ]);
})
-> map ( function ( $ item ) {
return strtoupper ( $ item );
});
// ['D', 'E', 'F']
validate
如果給定的$callback
對每個項目都傳回 true,則傳回true
。如果$callback
是字串或數組,則將其視為驗證規則。
collect ([ ' foo ' , ' foo ' ])-> validate ( function ( $ item ) {
return $ item === ' foo ' ;
}); // returns true
collect ([ ' [email protected] ' , ' bla ' ])-> validate ( ' email ' ); // returns false
collect ([ ' [email protected] ' , ' [email protected] ' ])-> validate ( ' email ' ); // returns true
weightedRandom
按權重返回隨機項目。在這個例子中,帶有a
的項目被挑選的機會最大,而帶有c
的項目被挑選的機會最少。
// pass the field name that should be used as a weight
$ randomItem = collect ([
[ ' value ' => ' a ' , ' weight ' => 30 ],
[ ' value ' => ' b ' , ' weight ' => 20 ],
[ ' value ' => ' c ' , ' weight ' => 10 ],
])-> weightedRandom ( ' weight ' );
或者,您可以傳遞可呼叫函數來取得權重。
$ randomItem = collect ([
[ ' value ' => ' a ' , ' weight ' => 30 ],
[ ' value ' => ' b ' , ' weight ' => 20 ],
[ ' value ' => ' c ' , ' weight ' => 10 ],
])-> weightedRandom ( function ( array $ item ) {
return $ item [ ' weight ' ];
});
withSize
建立一個包含指定數量項目的新集合。
Collection:: withSize ( 1 )-> toArray (); // return [1];
Collection:: withSize ( 5 )-> toArray (); // return [1,2,3,4,5];
請參閱變更日誌以了解最近變更的更多資訊。
$ composer test
詳細資訊請參閱貢獻。
如果您發現有關安全的錯誤,請發送郵件至 [email protected],而不是使用問題追蹤器。
Spatie 是一家位於比利時安特衛普的網頁設計公司。您可以在我們的網站上找到所有開源專案的概述。
麻省理工學院許可證 (MIT)。請參閱許可證文件以獲取更多資訊。