이 저장소에는 몇 가지 유용한 컬렉션 매크로가 포함되어 있습니다.
Spatie는 벨기에 앤트워프에 본사를 둔 웹 디자인 에이전시입니다. 당사 웹사이트에서 당사의 모든 오픈 소스 프로젝트에 대한 개요를 확인할 수 있습니다.
우리는 동급 최고의 오픈 소스 패키지를 만드는 데 많은 리소스를 투자합니다. 유료 제품 중 하나를 구매하여 우리를 지원할 수 있습니다.
귀하가 사용하고 있는 당사 패키지를 언급하면서 귀하의 고향에서 엽서를 보내주셔서 진심으로 감사드립니다. 연락처 페이지에서 주소를 확인하실 수 있습니다. 우리는 수신된 모든 엽서를 가상 엽서 월에 게시합니다.
작곡가를 통해 패키지를 가져올 수 있습니다.
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;대체 매개변수로 사용할 두 번째 매개변수를 전달할 수도 있습니다.
$ 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 ); // 3second두 번째 인덱스에서 항목을 검색합니다.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> second (); // 2third세 번째 인덱스에서 항목을 검색합니다.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> third (); // 3fourth네 번째 인덱스에서 항목을 검색합니다.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fourth (); // 4fifth다섯 번째 인덱스에서 항목을 검색합니다.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> fifth (); // 5sixth여섯 번째 인덱스에서 항목을 검색합니다.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> sixth (); // 6seventh일곱 번째 인덱스에서 항목을 검색합니다.
$ data = new Collection ([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]);
$ data -> seventh (); // 7eighth여덟 번째 인덱스에서 항목을 검색합니다.
$ 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;대체 매개변수로 사용할 두 번째 매개변수를 전달할 수도 있습니다.
$ 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 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 와 매우 유사하지만 두 가지 주요 차이점이 있습니다.
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첫 번째 매개변수로 주어진 콜러블을 사용하여 첫 번째 항목을 검색합니다. 값이 없으면 두 번째 매개변수의 값을 컬렉션에 푸시합니다. 두 번째 매개변수로 콜러블을 전달할 수 있습니다.
이 방법은 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 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 ); 이는 페이지당 5개의 항목으로 $posts 의 내용을 페이지로 매깁니다. paginate 몇 가지 옵션을 허용합니다. 자세한 가이드는 Laravel 문서를 참조하세요.
paginate(int $perPage = 15, string $pageName = 'page', ?int $page = null, ?int $total = null, array $options = [])
path "점" 표기법을 사용하여 다차원 데이터가 포함된 컬렉션의 항목을 반환합니다. 네이티브 컬렉션의 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 ); 이는 페이지당 5개의 항목으로 $posts 의 내용을 페이지로 매깁니다. 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 로 전달되면 키와 대체(fallback)가 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 로 지정했지만 컬렉션 자체는 데이터베이스 트랜잭션처럼 작동합니다. 따라서 예외가 발생하면 원래 컬렉션(시도 전)이 반환됩니다.
핸들러에 두 번째 매개변수를 추가하면 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 자세한 내용은 CONTRIBUTING을 참조하세요.
보안 관련 버그를 발견한 경우 이슈 트래커를 사용하는 대신 [email protected]로 메일을 보내주세요.
Spatie는 벨기에 앤트워프에 본사를 둔 웹 디자인 에이전시입니다. 당사 웹사이트에서 당사의 모든 오픈 소스 프로젝트에 대한 개요를 확인할 수 있습니다.
MIT 라이센스(MIT). 자세한 내용은 라이센스 파일을 참조하십시오.