このリポジトリには、いくつかの便利なコレクション マクロが含まれています。
Spatie は、ベルギーのアントワープに拠点を置くウェブデザイン会社です。当社のすべてのオープンソース プロジェクトの概要は、当社の Web サイトでご覧いただけます。
私たちはクラス最高のオープンソース パッケージの作成に多くのリソースを投資しています。有料製品のいずれかを購入することで、私たちをサポートできます。
当社のどのパッケージを使用しているかについて、故郷から葉書を送っていただき、誠にありがとうございます。当社の住所は、お問い合わせページに記載されています。受け取ったすべてのポストカードをバーチャル ポストカード ウォールに公開します。
Composer を介してパッケージを取り込むことができます。
composer require spatie/laravel-collection-macrosパッケージは自動的に登録されます。
afteratsecondthirdfourthfifthsixthseventheighthninthtenthgetNthbeforecatchchunkBycollectBycontainsAnycontainsAlleachConsextractfilterMapfirstOrFailfirstOrPushfromPairsgetCaseInsensitiveglobgroupByModelhasCaseInsensitiveheadififAnyifEmptyinsertAfterinsertAfterKeyinsertAtinsertBeforeinsertBeforeKeynonepaginatepathpluckManypluckManyValuespluckToArrayprioritizerecursiverotatesectionBysimplePaginatesliceBeforetailtrytoPairstransposevalidateweightedRandomwithSizeafterコレクションから次のアイテムを入手します。
$ 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;フォールバックとして使用する 2 番目のパラメーターを渡すこともできます。
$ 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 ); // 3second2 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> second (); // 2third3 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> third (); // 3fourth4 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fourth (); // 4fifth5 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fifth (); // 5sixth6 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> sixth (); // 6seventh7 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> seventh (); // 7eighth8 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> eighth (); // 8ninth9 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> ninth (); // 9tenth10 番目のインデックスにある項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> tenth (); // 10getNthn番目の項目の項目を取得します。
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ]);
$ data -> getNth ( 11 ); // 11beforeコレクションから前のアイテムを取得します。
$ 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;フォールバックとして使用する 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])フォールバックとして使用する 2 番目のパラメーターを渡すこともできます。
$ collection = collect ([
' foo ' => [ 1 , 2 , 3 ],
' bar ' => [ 4 , 5 , 6 ],
]);
$ collection -> collectBy ( ' baz ' , [ ' Nope ' ]); // Collection(['Nope'])containsAny指定された値が 1 つ以上コレクションに存在する場合、 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 falsecontainsAll指定されたすべての値がコレクション内に存在する場合は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 trueeachCons指定されたチャンク サイズからコレクション内の次の連続する近傍を取得します。オプションのパラメータ$preserveKeys trueとして渡すと、元のキーが保存されます。
collect ([ 1 , 2 , 3 , 4 ])-> eachCons ( 2 ); // return collect([[1, 2], [2, 3], [3, 4]])extractコレクションからキーを抽出します。これは、 onlyと非常に似ていますが、2 つの大きな違いがあります。
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 SpatieCollectionMacrosExceptionsCollectionItemNotFoundfirstOrPush最初のパラメータとして指定された呼び出し可能オブジェクトを使用して、最初の項目を取得します。値が存在しない場合は、2 番目のパラメーターの値をコレクションにプッシュします。呼び出し可能オブジェクトを 2 番目のパラメーターとして渡すことができます。
このメソッドは、キャッシュされたクラス プロパティを扱う場合、つまり API から取得した値や計算量の多い関数を複数回使用するためにコレクションに格納する場合に非常に役立ちます。
$ collection = collect ([ 1 , 2 , 3 ])-> firstOrPush ( fn ( $ item ) => $ item === 4 , 4 );
$ collection -> toArray (); // returns [1, 2, 3, 4]場合によっては、プッシュ先のターゲット コレクションを指定したい場合があります。これを 3 番目のパラメータとして渡すことができます。
$ 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 nullif 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 truepaginateコレクション内の項目の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という名前が付けられていますが、コレクション自体はデータベース トランザクションのように動作します。したがって、例外がスローされると、元のコレクション (試行前) が返されます。
ハンドラーに 2 番目のパラメーターを追加することで、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 trueweightedRandom重量に基づいてランダムなアイテムを返します。この例では、 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]; 最近の変更点の詳細については、CHANGELOG を参照してください。
$ composer test 詳細については、「貢献」を参照してください。
セキュリティに関するバグを見つけた場合は、問題トラッカーを使用する代わりに [email protected] にメールを送信してください。
Spatie は、ベルギーのアントワープに拠点を置くウェブデザイン会社です。当社のすべてのオープンソース プロジェクトの概要は、当社の Web サイトでご覧いただけます。
MIT ライセンス (MIT)。詳細については、ライセンス ファイルを参照してください。