모으다
소개
IlluminateSupportCollection
클래스는 배열 데이터 처리를 위해 더 읽기 쉽고 편리한 캡슐화를 제공합니다. 구체적인 예는 아래 코드를 참조하세요. collect
도우미 함수를 사용하여 배열에서 새 컬렉션 인스턴스를 만들고 각 요소에 대해 strtoupper
함수를 실행한 다음 모든 빈 요소를 삭제합니다. IlluminateSupportCollection
类提供了一个更具可读性和更便于处理数组数据的封装。具体例子请查看下面代码。我们使用 collect
辅助函数从数组中创建一个新的集合实例,对其中每一个元素执行 strtoupper
函数之后再删除所有的空元素:
$collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); });
正如你所见, Collection
类允许你链式调用其它方法,以达到在底层数组上流畅的执行 map 和 reduce 操作,通常,集合是不可变的,这意味着每一个 Collection
方法都会返回一个新的 Collection
实例。
创建集合
如上所述, collect
辅助函数会为指定的数组返回一个新的 IlluminateSupportCollection
实例。因此,我们可以这样轻松的创建一个集合:
$collection = collect([1, 2, 3]);
{tip} 通常,Eloquent 查询的结果返回的内容都是
Collection
实例。
扩展集合
集合都是「可宏扩展」(macroable) 的,它允许你在执行时将其它方法添加到 Collection
类。例如,通过下面的代码在 Collection
类中添加一个 toUpper
use Illuminate\Support\Str;Collection::macro('toUpper', function () { return $this->map(function ($value) { return Str::upper($value); }); });$collection = collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND']As you As 보시다시피,
Collection
클래스를 사용하면 다른 메소드에 대한 호출을 연결하여 기본 배열에서 맵 및 축소 작업을 원활하게 수행할 수 있습니다. 일반적으로 컬렉션은 변경할 수 없습니다. 즉, 각 컬렉션 code> 메소드는 모두 새로운 Collection
인스턴스를 반환합니다. 컬렉션 만들기
위에서 언급했듯이 수집 code> 도우미 함수는 지정된 배열에 대한 새로운 IlluminateSupportCollection
인스턴스를 반환합니다. 따라서 다음과 같은 컬렉션을 쉽게 생성할 수 있습니다: collect([1, 2, 3])->all();// [1, 2, 3]
{tip} 일반적으로 Eloquent 쿼리에서 반환되는 결과는 Collection
인스턴스입니다. 🎜🎜🎜🎜🎜컬렉션 확장
🎜컬렉션은 "매크로 가능" " "확장 가능"(매크로 가능) - 실행 시 Collection
클래스에 추가 메서드를 추가할 수 있습니다. 예를 들어 다음 코드를 사용하여 Collection
클래스에 toUpper
메서드를 추가합니다. 🎜$average = collect([['foo' => 10],
['foo' => 10],
['foo' => 20],
['foo' => 40]])->avg('foo');
// 20
$average = collect([1, 1, 2, 4])->avg();
// 2
🎜일반적으로 서비스 공급자 내부에서 컬렉션 매크로를 선언해야 합니다. 🎜🎜🎜🎜🎜🎜🎜사용 가능한 방법
문서에 따라 필요한 경우 컬렉션의 원본을 저장할 수 있는 Collection
类的每个方法。请牢记,所有方法都可以通过链式访问的形式优雅的操作数组。而且,几乎所有的方法都会返回一个新的 Collection
인스턴스를 살펴보겠습니다.
ㅋㅋㅋ containsStrictcount
crossJoin
dd
ㅋㅋㅋ filter
first
firstWhere
flatMap
flatten
flip
forget
forPage
get
groupBy
has
implode
intersect
intersectByKeys
isEmpty
isNotEmpty
keyBy
keys
last
macro
make
map
mapInto
mapSpread
mapToGroups
mapWithKeys
max
median
merge
min
mode
nth
only
pad
partition
pipe
pluck
pop
prep 끝
당겨
밀어
put
random
reduce
reject
reverse
search
shift
shuffle
slice
some
sort
sortBy
sortByDesc
sortKeys
sortKeysDesc
splice
split
sum
take
tap
times
toArray
toJson
transform
union
고유함
uniqueStrict
unless
unlessEmpty
unlessNotEmpty
unwrap
values
when
비어 있을 때
whenNotEmpty
where
whereStrict
whereBetween
whereIn
whereInStrict
whereInstanceOf
whereNotBetween
whereNotIn
whereNotInStrict
wrap
zip
방법 목록
all()
all()
all
方法返回该集合表示的底层数组:
$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
average()
avg
方法的别名。
avg()
avg
方法返回给定键的 平均值 :
@foreach ($products->chunk(3) as $chunk)
<div class="row">
@foreach ($chunk as $product)
<div class="col-xs-4">
{{ $product->name }}
</div>
@endforeach
</div>
@endforeach
chunk()
chunk
方法将集合拆成多个给定大小的小集合:
$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]
这个方法在使用网格系统的 视图 中特别适用,例如 Bootstrap。 想象你有一个 Eloquent 模型的集合要在网格中显示:
$collection = collect(['name', 'age']);
$combined = $collection->combine(['George', 29]);
$combined->all();
// ['name' => 'George', 'age' => 29]
collapse()
collapse
all
메서드는 컬렉션이 나타내는 기본 배열을 반환합니다:
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// ['John Doe', 'Jane Doe', 'Johnny Doe']
average()
메소드 별칭입니다. 🎜🎜🎜🎜🎜avg()
🎜avg
메소드는 주어진 키에 대한 평균 🎜을 반환합니다: 🎜$collection = collect(['name' => 'Desk', 'price' => 100]);
$collection->contains('Desk');
// true
$collection->contains('New York');
// false
🎜🎜 🎜🎜chunk()
🎜chunk
메소드는 컬렉션을 여러 개의 Small로 분할합니다. 주어진 크기의 컬렉션: 🎜$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$collection->contains('product', 'Bookcase');
// false
🎜이 방법은 Bootstrap🎜과 같은 그리드 시스템을 사용하는 뷰에서 특히 잘 작동합니다. 그리드에 표시할 Eloquent 모델 컬렉션이 있다고 상상해 보세요: 🎜$collection = collect([1, 2, 3, 4, 5]);
$collection->contains(function ($value, $key) {
return $value > 5;
});
// false
🎜🎜🎜🎜< code >collapse()
🎜collapse
메소드는 여러 배열 모음을 배열 모음으로 병합합니다. 🎜$collection = collect([1, 2, 3, 4]);
$collection->count();
// 4
🎜🎜🎜🎜🎜🎜combine()
combine()
combine
方法可以将一个集合的值作为键,再将另一个数组或集合的值作为值合并成一个集合:
$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'],
]
*/
concat()
concat
方法将给定的 数组
或集合值追加到集合的末尾:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dd();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
contains()
contains
方法判断集合是否包含指定的集合项:
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
你也可以使用 contains
方法传递一组键 / 值对,可以判断该键 / 值对是否存在于集合中:
$collection = collect([
'color' => 'orange',
'type' => 'fruit',
'remain' => 6
]);
$diff = $collection->diffAssoc([
'color' => 'yellow',
'type' => 'fruit',
'remain' => 3,
'used' => 6
]);
$diff->all();
// ['color' => 'orange', 'remain' => 6]
最后,你也可以用 contains
方法传递一个回调函数来执行自己的真实测试:
$collection = collect([
'one' => 10,
'two' => 20,
'three' => 30,
'four' => 40,
'five' => 50,
]);
$diff = $collection->diffKeys([
'two' => 2,
'four' => 4,
'six' => 6,
'eight' => 8,
]);
$diff->all();
// ['one' => 10, 'three' => 30, 'five' => 50]
contains
方法在检查集合项的值时使用「宽松」比较,这意味着具有整数值的字符串将被视为等于相同值的整数。相反 containsStrict
方法则是使用「严格」比较进行过滤。
containsStrict()
这个方法和 contains
方法类似,但是它却是使用了「严格」比较来比较所有的值。
count()
count
方法返回这个集合内集合项的总数量:
$collection = collect(['John Doe', 'Jane Doe']);
$collection->dump();
/*
Collection {
#items: array:2 [
0 => "John Doe"
1 => "Jane Doe"
]
}
*/
crossJoin()
crossJoin
方法交叉连接指定数组或集合的值,返回所有可能排列的笛卡尔积:
$collection->each(function ($item, $key) {
//
});
dd()
dd
方法用于打印集合项并中断脚本执行:
$collection->each(function ($item, $key) {
if (/* 某些条件 */ )
{
return false;
}
});
如果你不想中断执行脚本,请使用 dump
方法代替。
diff()
diff
方法将集合与其它集合或纯 PHP 数组
进行值的比较。然后返回原集合中存在而指定集合中不存在的值:
$collection = collect([['John Doe', 35], ['Jane Doe', 33]]);
$collection->eachSpread(function ($name, $age) {
//
});
diffAssoc()
diffAssoc
方法与另外一个集合或基于它的键和值的 PHP 数组
combine
메서드는 집합의 값을 키로 사용한 다음 다른 배열의 값을 결합하거나 값으로 집합을 세트 구성:
$collection->eachSpread(function ($name, $age) {
return false;
});
concat()
concat
메소드는 주어진 배열
또는 컬렉션 값을 컬렉션 끝에 추가합니다: 🎜collect([1, 2, 3, 4])->every(function ($value, $key) {
return $value > 2;
});
// false
🎜🎜🎜🎜🎜contains()
🎜contains
메서드는 컬렉션에 지정된 컬렉션 항목이 포함되어 있는지 확인합니다. 🎜$collection = collect([]);
$collection->every(function($value, $key)
{
return $value > 2;
});
// true
🎜또한 < The code>contains 메소드를 사용하여 키/값 쌍 세트를 전달하고, 이를 사용하여 키/값 쌍이 컬렉션에 존재하는지 확인하는 데 사용할 수 있습니다. 🎜$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);
$filtered->all();
// ['product_id' => 1]
🎜마지막으로 다음을 사용할 수도 있습니다. 실제 테스트를 수행하기 위해 콜백 함수를 전달하는 contains
메서드: 🎜$collection = collect([1, 2, 3, 4]);
$filtered = $collection->filter(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [3, 4]
🎜contains
메서드는 컬렉션 값을 확인할 때 "완화된" 비교를 사용합니다. 즉, 정수 값을 가진 문자열은 동일한 값의 정수와 동일한 것으로 간주됩니다. 이와 대조적으로 containsStrict
🎜 메서드는 필터링에 "엄격한" 비교를 사용합니다. 🎜🎜🎜🎜🎜🎜containsStrict()
🎜이 메서드는 < a href="#method-contains">contains
🎜와 동일 메서드는 유사하지만 "엄격한" 비교를 사용하여 모든 값을 비교합니다. 🎜🎜🎜🎜🎜🎜count()
🎜count
메소드는 이 컬렉션에 있는 총 컬렉션 항목 수를 반환합니다. 🎜$collection = collect([1, 2, 3, null, false, '', 0, []]);
$collection->filter()->all();
// [1, 2, 3]
🎜🎜🎜🎜🎜 crossJoin()
🎜crossJoin
메소드는 지정된 배열 또는 컬렉션의 값을 교차 조인하여 가능한 모든 순열의 데카르트 곱을 반환합니다. 🎜collect([1, 2, 3, 4])->first(function ($value, $key) {
return $value > 2;
});
// 3
🎜🎜🎜🎜🎜dd()
🎜dd
메소드는 컬렉션 항목을 인쇄하는 데 사용되며 스크립트 실행을 중단합니다: 🎜collect([1, 2, 3, 4])->first();
// 1
🎜 스크립트 실행을 중단하지 않으려면 대신 dump
🎜 메소드를 사용하세요. . 🎜🎜🎜🎜🎜🎜diff()
🎜diff
메소드는 컬렉션의 값을 다른 컬렉션 또는 순수 PHP 배열
과 비교합니다. 그런 다음 원래 컬렉션에는 존재하지만 지정된 컬렉션에는 존재하지 않는 값을 반환합니다. 🎜$collection = collect([
['name' => 'Regena', 'age' => null],
['name' => 'Linda', 'age' => 14],
['name' => 'Diego', 'age' => 23],
['name' => 'Linda', 'age' => 84],
]);
$collection->firstWhere('name', 'Linda');
// ['name' => 'Linda', 'age' => 14]
🎜🎜🎜🎜🎜 diffAssoc()
🎜diffAssoc
메서드는 키와 값을 기반으로 다른 컬렉션이나 PHP 배열
과 비교합니다. 이 메소드는 원래 컬렉션이 지정된 컬렉션에 존재하지 않는 키/값 쌍을 반환합니다. 🎜$collection->firstWhere('age', '>=', 18);
// ['name' => 'Diego', 'age' => 23]
🎜🎜🎜🎜🎜🎜diffKeys()
diffKeys()
diffKeys
方法和另外一个集合或 PHP 数组
的键进行比较,然后返回原集合中存在而指定集合中不存在键所对应的键 / 值对:
$collection->firstWhere('age');
// ['name' => 'Linda', 'age' => 14]
dump()
dump
方法用于打印集合项:
$collection = collect([
['name' => 'Sally'],
['school' => 'Arkansas'],
['age' => 28]
]);
$flattened = $collection->flatMap(function ($values) {
return array_map('strtoupper', $values);
});
$flattened->all();
// ['name' => 'SALLY', 'school' => 'ARKANSAS', 'age' => '28'];
如果要在打印集合后终止执行脚本,请使用 dd
方法代替。
each()
each
方法用于循环集合项并将其传递到回调函数中:
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
如果你想中断对集合项的循环,那么就在你的回调函数中返回 false
:
$collection = collect([
'Apple' => [
['name' => 'iPhone 6S', 'brand' => 'Apple'],
],
'Samsung' => [
['name' => 'Galaxy S7', 'brand' => 'Samsung']
],
]);
$products = $collection->flatten(1);$products->values()->all();
/*
[
['name' => 'iPhone 6S', 'brand' => 'Apple'],
['name' => 'Galaxy S7', 'brand' => 'Samsung'],
]
*/
eachSpread()
eachSpread
方法用于循环集合项,将每个嵌套集合项的值传递给回调函数:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$flipped = $collection->flip();$flipped->all();
// ['taylor' => 'name', 'laravel' => 'framework']
你可以通过在回调函数里返回 false
来中断循环:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$collection->forget('name');$collection->all();
// ['framework' => 'laravel']
every()
every
方法可用于验证集合中的每一个元素是否通过指定的条件测试:
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);$chunk->all();
// [4, 5, 6]
如果集合为空, every
将返回 true:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('name');
// taylor
except()
except
方法返回集合中除了指定键之外的所有集合项:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
$value = $collection->get('foo', 'default-value');
// default-value
与 except
对应的是 only 方法。
filter()
filter
方法使用给定的回调函数过滤集合,只保留那些通过指定条件测试的集合项:
$collection->get('email', function () {
return 'default-value';
});
// default-value
如果没有提供回调函数,集合中所有返回 false
的元素都会被移除:
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
与 filter
对应的是 reject 方法。
first()
first
方法返回集合中通过指定条件测试的第一个元素:
$grouped = $collection->groupBy(function ($item, $key) {
return substr($item['account_id'], -3);
});
$grouped->toArray();
/*
[
'x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
你也可以不传入参数调用 first
方法来获取集合中的第一个元素。如果集合为空,则会返回 null
diffKeys
메서드는 다른 컬렉션이나 PHP 배열
의 키를 비교한 다음 원본의 키를 반환합니다. 컬렉션 키에 해당하는 키/값 쌍이 지정된 컬렉션에 존재하지 않습니다:
$data = new Collection([
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
]);
$result = $data->groupBy([
'skill',
function ($item) {
return $item['roles'];
},
],
$preserveKeys = true);
/*
[
1 => [
'Role_1' => [
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
],
'Role_2' => [
20 => ['user' => 2, 'skill' => 1, 'roles' => ['Role_1', 'Role_2']],
],
'Role_3' => [
10 => ['user' => 1, 'skill' => 1, 'roles' => ['Role_1', 'Role_3']],
],
],
2 => [
'Role_1' => [
30 => ['user' => 3, 'skill' => 2, 'roles' => ['Role_1']],
],
'Role_2' => [
40 => ['user' => 4, 'skill' => 2, 'roles' => ['Role_2']],
],
],
];
*/
dump()
dump
메소드는 컬렉션 항목을 인쇄하는 데 사용됩니다. 🎜$collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]);
$collection->has('product');
// true
$collection->has(['product', 'amount']);
// true
$collection->has(['amount', 'price']);
// false
🎜 컬렉션을 인쇄한 후 스크립트 실행을 종료하려면 다음을 사용하세요. 대신 dd
🎜 메소드를 사용하세요. 🎜🎜🎜🎜🎜🎜각()
🎜각
메서드는 컬렉션 항목을 반복하여 콜백 함수에 전달하는 데 사용됩니다. 🎜$collection = collect([
['account_id' => 1,'product' => 'Desk'],
['account_id' => 2, 'product' => 'Chair'],
]);
$collection->implode('product', ', ');
// Desk, Chair
🎜 컬렉션 항목에 대한 루프를 중단하려면 콜백 함수에서 false
를 반환하세요. 🎜collect([1, 2, 3, 4, 5])->implode('-');
// '1-2-3-4-5'
🎜🎜🎜🎜🎜eachSpread()
🎜 EachSpread
메서드는 컬렉션 항목을 반복하는 데 사용되며 중첩된 각 컬렉션 항목의 값을 콜백 함수에 전달합니다. 🎜$collection = collect(['Desk', 'Sofa', 'Chair']);
$intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']);
$intersect->all();
// [0 => 'Desk', 2 => 'Chair']
🎜콜백에서 false
를 반환하여 루프를 중단할 수 있습니다. 함수: 🎜 $collection = collect([
'serial' => 'UX301',
'type' => 'screen',
'year' => 2009
]);
$intersect = $collection->intersectByKeys([
'reference' => 'UX404',
'type' => 'tab',
'year' => 2011
]);
$intersect->all();
// ['type' => 'screen', 'year' => 2009]
🎜🎜🎜🎜🎜every()
🎜< code>every 메소드를 사용하면 컬렉션의 각 요소가 지정된 조건 테스트를 통과하는지 확인할 수 있습니다. 🎜collect([])->isEmpty();
// true
🎜 컬렉션이 비어 있으면 every
는 true를 반환합니다. 🎜collect([])->isNotEmpty();
// false
🎜 🎜🎜🎜🎜제외()
🎜제외 code> 메소드는 컬렉션을 반환합니다. 지정된 키 🎜$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keyed = $collection->keyBy('product_id');$keyed->all();
/*
[
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
🎜 및 제외
를 제외한 모든 컬렉션 항목은 only🎜 메소드에 해당합니다. 🎜🎜🎜🎜🎜🎜filter()
🎜필터
메서드는 지정된 콜백 함수를 사용하여 컬렉션을 필터링하고 지정된 조건 테스트를 통과하는 컬렉션 항목만 유지합니다. 🎜$keyed = $collection->keyBy(function ($item) {
return strtoupper($item['product_id']);
});
$keyed->all();
/*
[
'PROD-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'PROD-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
🎜콜백 함수가 제공되지 않으면 false를 반환하는 컬렉션의 모든 요소 code>가 제거됩니다. 🎜$collection = collect([
'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$keys = $collection->keys();
$keys->all();
// ['prod-100', 'prod-200']
🎜 및 filter
는 reject🎜 메소드에 해당합니다. 🎜🎜🎜🎜🎜🎜first()
🎜first
메서드는 지정된 조건 테스트를 통과한 컬렉션의 첫 번째 요소를 반환합니다. 🎜collect([1, 2, 3, 4])->last(function ($value, $key) {
return $value < 3;
});
// 2
🎜 컬렉션의 첫 번째 요소를 가져오기 위해 매개변수를 전달하지 않고 first
메서드를 호출할 수도 있습니다. 컬렉션이 비어 있으면 null
이 반환됩니다. 🎜collect([1, 2, 3, 4])->last();
// 4
🎜🎜🎜🎜🎜🎜firstWhere()
firstWhere()
firstWhere
方法返回集合中含有指定键 / 值对的第一个元素:
$collection = collect([1, 2, 3, 4, 5]);
$multiplied = $collection->map(function ($item, $key) {
return $item * 2;
});
$multiplied->all();
// [2, 4, 6, 8, 10]
你也可以使用运算符来调用 firstWhere
方法:
class Currency{
/**
* Create a new currency instance.
*
* @param string $code
* @return void
*/
function __construct(string $code)
{
$this->code = $code;
}
}
$collection = collect(['USD', 'EUR', 'GBP']);
$currencies = $collection->mapInto(Currency::class);
$currencies->all();
// [Currency('USD'), Currency('EUR'), Currency('GBP')]
和 where 方法一样,你可以将一个参数传递给 firstWhere
方法。在这种情况下, firstWhere
方法将返回指定键的值为「真」的第一个集合项:
$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunks = $collection->chunk(2);
$sequence = $chunks->mapSpread(function ($even, $odd) {
return $even + $odd;
});
$sequence->all();
// [1, 5, 9, 13, 17]
flatMap()
flatMap
方法遍历集合并将其中的每个值传递到给定的回调函数。可以通过回调函数修改集合项并返回它们,从而形成一个被修改过的新集合。然后,集合转化的数组是同级的:
$collection = collect([
[
'name' => 'John Doe',
'department' => 'Sales',
],
[
'name' => 'Jane Doe',
'department' => 'Sales',
],
[
'name' => 'Johnny Doe',
'department' => 'Marketing',
]
]);
$grouped = $collection->mapToGroups(function ($item, $key) {
return [$item['department'] => $item['name']];
});
$grouped->toArray();
/*
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']
flatten()
flatten
方法将多维集合转为一维集合:
$collection = collect([
[
'name' => 'John',
'department' => 'Sales',
'email' => 'john@example.com'
],
[
'name' => 'Jane',
'department' => 'Marketing',
'email' => 'jane@example.com'
]
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
$keyed->all();
/*
[
'john@example.com' => 'John',
'jane@example.com' => 'Jane',
]
*/
你可以选择性地传入「深度」参数:
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
// 20
$max = collect([1, 2, 3, 4, 5])->max();
// 5
在这个例子里,调用 flatten
时不传入深度参数的话也会将嵌套数组转成一维的,然后返回 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']
。传入深度参数能让你限制设置返回数组的层数。
flip()
flip
方法将集合的键和对应的值进行互换:
$median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');
// 15
$median = collect([1, 1, 2, 4])->median();
// 1.5
forget()
forget
方法将通过指定的键来移除集合中对应的内容:
$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();
// ['product_id' => 1, 'price' => 200, 'discount' => false]
{note} 与大多数集合的方法不同的是, forget
不会返回修改后的新集合;它会直接修改原集合。
forPage()
forPage
方法返回一个含有指定页码数集合项的新集合。这个方法接受页码数作为其第一个参数,每页显示的项数作为其第二个参数:
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
$merged->all();
// ['Desk', 'Chair', 'Bookcase', 'Door']
get()
get
方法返回指定键的集合项,如果该键在集合中不存在,则返回 null
firstWhere
메서드는 지정된 키/값 쌍을 포함하는 컬렉션의 첫 번째 요소를 반환합니다.
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
// 10
$min = collect([1, 2, 3, 4, 5])->min();
// 1
연산자를 사용하여 호출할 수도 있습니다. firstWhere
메서드:
$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');
// [10]
$mode = collect([1, 1, 2, 4])->mode();
// [1]
메서드와 마찬가지로 firstWhere
메서드에 인수를 전달할 수 있습니다. 이 경우 firstWhere
메소드는 지정된 키에 대해 값이 "true"인 첫 번째 컬렉션 항목을 반환합니다: $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']);
$collection->nth(4);
// ['a', 'e']
flatMap()
🎜 flatMap
메서드는 컬렉션을 반복하고 컬렉션의 각 값을 특정 A에 전달합니다. 콜백 함수. 컬렉션 항목을 수정하고 콜백 함수를 통해 이를 반환하여 수정된 새 컬렉션을 형성할 수 있습니다. 그런 다음 컬렉션에 의해 변환된 배열은 동일한 수준입니다. 🎜$collection->nth(4, 1);
// ['b', 'f']
🎜🎜🎜🎜🎜Flatten ()< /code>🎜Flatten
메소드는 다차원 컬렉션을 1차원 컬렉션으로 변환합니다. 🎜$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
$filtered = $collection->only(['product_id', 'name']);
$filtered->all();
// ['product_id' => 1, 'name' => 'Desk']
🎜선택적으로 "깊이" 매개변수를 전달할 수 있습니다: 🎜$collection = collect(['A', 'B', 'C']);
$filtered = $collection->pad(5, 0);
$filtered->all();
// ['A', 'B', 'C', 0, 0]
$filtered = $collection->pad(-5, 0);
$filtered->all();
// [0, 0, 'A', 'B', 'C']
🎜 이 예에서는 Flatten
을 호출합니다. 깊이 매개변수가 전달되지 않으면 중첩 배열이 1차원으로 변환된 다음 ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung'이 반환됩니다 ]
. 깊이 매개변수를 전달하면 반환되는 배열의 수준 수를 제한할 수 있습니다. 🎜🎜🎜🎜🎜🎜flip()
🎜플립
이 메소드는 컬렉션의 키를 해당 값과 교환합니다: 🎜$collection = collect([1, 2, 3, 4, 5, 6]);
list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) {
return $i < 3;
});
$underThree->all();
// [1, 2]
$equalOrAboveThree->all();
// [3, 4, 5, 6]
🎜🎜🎜🎜🎜< code>forget() 🎜forget
메소드는 지정된 키로 컬렉션에서 해당 콘텐츠를 제거합니다: 🎜$collection = collect([1, 2, 3]);
$piped = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6
🎜{note} 및 대부분의 컬렉션 차이점은 forget
은 수정된 새 컬렉션을 반환하지 않고 원래 컬렉션을 직접 수정한다는 것입니다. 🎜
🎜🎜🎜🎜🎜forPage()
🎜 forPage
메소드는 컬렉션 항목의 지정된 페이지 번호를 포함하는 새 컬렉션을 반환합니다. 이 메소드는 페이지 번호를 첫 번째 매개변수로, 페이지당 표시되는 항목 수를 두 번째 매개변수로 받아들입니다: 🎜$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
🎜🎜🎜🎜🎜get()
🎜get
메소드는 지정된 키의 컬렉션 항목을 반환합니다. 컬렉션에 키가 없으면 반환됩니다. < code>null: 🎜$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
🎜 두 번째 매개변수로 선택한 기본값을 전달할 수 있습니다. 🎜$collection = collect([
['brand' => 'Tesla', 'color' => 'red'],
['brand' => 'Pagani', 'color' => 'white'],
['brand' => 'Tesla', 'color' => 'black'],
['brand' => 'Pagani', 'color' => 'orange'],
]);
$plucked = $collection->pluck('color', 'brand');
$plucked->all();
// ['Tesla' => 'black', 'Pagani' => 'orange']
🎜 콜백 함수를 기본값으로 전달할 수도 있습니다. 지정된 키가 존재하지 않으면 콜백 함수의 결과가 반환됩니다: 🎜$collection = collect([1, 2, 3, 4, 5]);
$collection->pop();
// 5
$collection->all();
// [1, 2, 3, 4]
🎜🎜🎜🎜🎜🎜groupBy()
groupBy()
groupBy
方法根据指定键对集合项进行分组:
$collection = collect([1, 2, 3, 4, 5]);
$collection->prepend(0);
$collection->all();
// [0, 1, 2, 3, 4, 5]
你可以传递一个回调函数用来代替一个字符串的 键
。这个回调函数应该返回你希望用来分组的键的值:
$collection = collect(['one' => 1, 'two' => 2]);
$collection->prepend(0, 'zero');
$collection->all();
// ['zero' => 0, 'one' => 1, 'two' => 2]
可以传递一个数组用于多重分组标准。每一个数组元素将对应多维数组内的相应级别:
$collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']);
$collection->pull('name');
// 'Desk'
$collection->all();
// ['product_id' => 'prod-100']
has()
has
方法判断集合中是否存在指定键:
$collection = collect([1, 2, 3, 4]);
$collection->push(5);
$collection->all();
// [1, 2, 3, 4, 5]
implode()
implode
方法用于合并集合项。其参数取决于集合项的类型。如果集合包含数组或对象,你应该传递你希望合并的属性的键,以及你希望放在值之间用来「拼接」的字符串:
$collection = collect(['product_id' => 1, 'name' => 'Desk']);
$collection->put('price', 100);
$collection->all();
// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
如果集合中包含简单的字符串或数值,只需要传入「拼接」用的字符串作为该方法的唯一参数即可:
$collection = collect([1, 2, 3, 4, 5]);
$collection->random();
// 4 - (retrieved randomly)
intersect()
intersect
方法从原集合中移除在指定 数组
或集合中不存在的任何值。生成的集合将会保留原集合的键:
$random = $collection->random(3);
$random->all();
// [2, 4, 5] - (retrieved randomly)
intersectByKeys()
intersectByKeys
方法从原集合中移除在指定 数组
或集合中不存在的任何键:
$collection = collect([1, 2, 3]);
$total = $collection->reduce(function ($carry, $item) {
return $carry + $item;
});
// 6
isEmpty()
如果集合为空,isEmpty
方法返回 true
,否则,返回 false
:
$collection->reduce(function ($carry, $item) {
return $carry + $item;}, 4);
// 10
isNotEmpty()
如果集合不为空,isNotEmpty
方法返回 true
,否则,返回 false
:
$collection = collect([1, 2, 3, 4]);
$filtered = $collection->reject(function ($value, $key) {
return $value > 2;
});
$filtered->all();
// [1, 2]
keyBy()
keyBy
方法以指定的键作为集合的键。如果多个集合项具有相同的键,则只有最后一个集合项会显示在新集合中:
$collection = collect(['a', 'b', 'c', 'd', 'e']);
$reversed = $collection->reverse();
$reversed->all();
/*
[
4 => 'e',
3 => 'd',
2 => 'c',
1 => 'b',
0 => 'a',
]
*/
你还可以在这个方法传递一个回调函数。该回调函数返回的值会作为该集合的键:
$collection = collect([2, 4, 6, 8]);
$collection->search(4);
// 1
keys()
keys
groupBy
메서드는 지정된 키에 따라 컬렉션 항목을 그룹화합니다.
$collection->search('4', true);
// false
문자열 대신 콜백 함수를 전달할 수 있습니다. 키
. 이 콜백 함수는 그룹화하려는 키의 값을 반환해야 합니다. $collection->search(function ($item, $key) {
return $item > 5;
});
// 2
여러 그룹화 기준에 대해 배열을 전달할 수 있습니다. 각 배열 요소는 다차원 배열 내의 해당 수준에 해당합니다.
$collection = collect([1, 2, 3, 4, 5]);
$collection->shift();
// 1
$collection->all();
// [2, 3, 4, 5]
🎜🎜🎜has ( )
🎜has
메소드는 지정된 키가 컬렉션에 존재하는지 여부를 확인합니다. 🎜$collection = collect([1, 2, 3, 4, 5]);
$shuffled = $collection->shuffle();
$shuffled->all();
// [3, 2, 5, 1, 4] - (generated randomly)
🎜🎜🎜🎜🎜implode()
🎜implode
메소드는 컬렉션 항목을 병합하는 데 사용됩니다. 해당 매개변수는 컬렉션 항목 유형에 따라 다릅니다. 컬렉션에 배열이나 개체가 포함된 경우 병합하려는 속성의 키와 값 사이에 삽입하려는 문자열을 전달하여 "연결"해야 합니다. 🎜$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4);
$slice->all();
// [5, 6, 7, 8, 9, 10]
🎜 컬렉션에 간단한 문자열이나 숫자가 포함된 경우 , 단지 이 메소드의 유일한 매개변수로 "접합"에 사용되는 문자열을 전달해야 합니다: 🎜$slice = $collection->slice(4, 2);
$slice->all();
// [5, 6]
🎜🎜🎜🎜 🎜intersect()
🎜intersect
메서드는 지정된 배열<에 존재하지 않는 모든 값을 원래 컬렉션에서 제거합니다. /code> 또는 컬렉션. 생성된 세트는 원래 세트의 키를 유지합니다: 🎜$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
🎜🎜🎜🎜🎜intersectByKeys() < /code> 🎜intersectByKeys
메소드는 지정된 배열
또는 컬렉션에 존재하지 않는 원래 컬렉션의 모든 키를 제거합니다. 🎜$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');$sorted->values()->all();
/*
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
*/
🎜🎜🎜🎜🎜isEmpty()
🎜컬렉션이 비어 있으면 isEmpty code> 메소드는 true
를 반환하고, 그렇지 않으면 false
를 반환합니다: 🎜$collection = collect([
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$sorted = $collection->sortBy(function ($product, $key) {
return count($product['colors']);
});
$sorted->values()->all();
/*
[
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]
*/
🎜🎜🎜🎜🎜isNotEmpty()
🎜컬렉션이 비어 있지 않으면 isNotEmpty
메서드는 true
그렇지 않으면 false
를 반환합니다. 🎜$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();$sorted->all();
/*
[
'first' => 'John',
'id' => 22345,
'last' => 'Doe',
]
*/
🎜🎜🎜🎜🎜keyBy ()
🎜keyBy
메서드는 지정된 키를 컬렉션의 키로 사용합니다. 여러 컬렉션 항목에 동일한 키가 있는 경우 마지막 컬렉션 항목만 새 컬렉션에 표시됩니다. 🎜$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]
🎜🎜🎜🎜🎜< code>keys( )🎜keys
메소드는 컬렉션의 모든 키를 반환합니다: 🎜$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]
🎜🎜🎜🎜🎜🎜last()
last()
last
方法返回集合中通过指定条件测试的最后一个元素:
$collection = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);
$groups->toArray();
// [[1, 2], [3, 4], [5]]
你也可以不传入参数调用 last
方法来获取集合中的最后一个元素。如果集合为空,则返回 null
:
collect([1, 2, 3, 4, 5])->sum();
// 15
macro()
静态 macro
方法允许你在运行时将方法添加至 Collection
类。关于更多信息,请参阅 扩展集合 的文档。
make()
静态 make
方法可以创建一个新的集合实例。请参阅 创建集合 部分。
map()
map
方法遍历集合并将每一个值传入给定的回调函数。该回调函数可以任意修改集合项并返回,从而生成被修改过集合项的新集合:
$collection = collect([
['name' => 'JavaScript: The Good Parts', 'pages' => 176],
['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);
$collection->sum('pages');
// 1272
{note} 与其它大多数集合方法一样,map
会返回一个新的集合实例;它不会修改原集合。如果你想修改原集合,请使用 transform
方法。
mapInto()
mapInto()
方法可以迭代集合,通过将值传递给构造函数来创建给定类的新实例:
$collection = collect([
['name' => 'Chair', 'colors' => ['Black']],
['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);
$collection->sum(function ($product) {
return count($product['colors']);
});
// 6
mapSpread()
mapSpread
方法可以遍历集合项,将每个嵌套项值给指定的回调函数。该回调函数可以自由修改该集合项并返回,从而生成被修改过集合项的新集合:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
mapToGroups()
mapToGroups
方法通过给定的回调函数对集合项进行分组。该回调函数应该返回一个包含单个键 / 值对的关联数组,从而生成一个分组值的新集合:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(-2);
$chunk->all();
// [4, 5]
mapWithKeys()
mapWithKeys
方法遍历集合并将每个值传入给定的回调函数。该回调函数将返回一个包含单个键 / 值对的关联数组:
collect([2, 4, 3, 1, 5])
->sort()
->tap(function ($collection) {
Log::debug('Values after sorting', $collection->values()->toArray());
})
->shift();
// 1
max()
max
last
메서드는 지정된 조건 테스트를 통과한 컬렉션의 마지막 요소를 반환합니다.
$collection = Collection::times(10, function ($number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
통과하지 않고 last
메소드에서 컬렉션의 마지막 요소를 가져옵니다. 컬렉션이 비어 있으면 null
을 반환합니다. $categories = Collection::times(3, function ($number) {
return factory(Category::class)->create(['name' => "Category No. $number"]);
});
$categories->all();
/*
[
['id' => 1, 'name' => 'Category #1'],
['id' => 2, 'name' => 'Category #2'],
['id' => 3, 'name' => 'Category #3'],
]
*/
🎜macro()
🎜정적 macro
메서드를 사용하면 런타임에 Collection
클래스에 메서드를 추가할 수 있습니다. 자세한 내용은 컬렉션 확장 🎜 문서를 참조하세요. 🎜🎜🎜🎜🎜🎜make()
🎜static make
메소드는 새로운 컬렉션 인스턴스를 생성합니다. 컬렉션 만들기 🎜 섹션을 참조하세요. 🎜🎜🎜🎜🎜🎜map()
🎜지도
메서드는 컬렉션을 반복하고 각 값을 지정된 콜백 함수에 전달합니다. 이 콜백 함수는 컬렉션 항목을 임의로 수정하고 반환함으로써 수정된 컬렉션 항목의 새 컬렉션을 생성할 수 있습니다. 🎜$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
🎜{note} 대부분의 다른 컬렉션 메서드와 마찬가지로 map
은 A new를 반환합니다. 컬렉션 인스턴스입니다. 원본 컬렉션을 수정하지 않습니다. 원본 컬렉션을 수정하려면 transform
🎜 메서드를 사용하세요. 🎜
🎜🎜🎜🎜🎜mapInto()
🎜 mapInto()
메서드는 컬렉션을 반복하여 생성자에 값을 전달하여 특정 클래스의 새 인스턴스를 생성할 수 있습니다. 🎜$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk", "price":200}'
🎜🎜🎜< div name= "e1f874" data-unique="e1f874">🎜🎜mapSpread()
🎜mapSpread
메소드는 컬렉션 항목을 순회하여 다음 값을 제공할 수 있습니다. 각 중첩 항목을 지정된 콜백 함수에 연결합니다. 콜백 함수는 컬렉션 항목을 자유롭게 수정하고 반환할 수 있으므로 수정된 컬렉션 항목의 새 컬렉션을 생성할 수 있습니다. 🎜$collection = collect([1, 2, 3, 4, 5]);
$collection->transform(function ($item, $key) {
return $item * 2;
});
$collection->all();
// [2, 4, 6, 8, 10]
🎜🎜🎜🎜🎜mapToGroups()
🎜mapToGroups
메소드는 주어진 콜백 함수를 통해 컬렉션 항목을 그룹화합니다. 콜백 함수는 단일 키/값 쌍을 포함하는 연관 배열을 반환하여 그룹화된 값의 새로운 컬렉션을 생성해야 합니다. 🎜$collection = collect([1 => ['a'], 2 => ['b']]);
$union = $collection->union([3 => ['c'], 1 => ['b']]);
$union->all();
// [1 => ['a'], 2 => ['b'], 3 => ['c']]
🎜🎜🎜🎜🎜mapWithKeys()
🎜mapWithKeys
메서드는 컬렉션을 반복하고 각 값을 지정된 콜백 함수에 전달합니다. 이 콜백 함수는 단일 키/값 쌍을 포함하는 연관 배열을 반환합니다: 🎜$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
🎜🎜🎜🎜🎜max()
🎜max
메소드는 지정된 키의 최대값을 반환합니다: 🎜$collection = collect([
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
🎜🎜🎜🎜🎜🎜median()
median()
median
方法返回指定键的 中值:
$unique = $collection->unique(function ($item) {
return $item['brand'].$item['type'];
});
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
*/
merge()
merge
方法将合并指定的数组或集合到原集合。如果给定的集合项的字符串键与原集合中的字符串键相匹配,则指定集合项的值将覆盖原集合的值:
$collection = collect([1, 2, 3]);
$collection->unless(true, function ($collection) {
return $collection->push(4);
});
$collection->unless(false, function ($collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 5]
如果指定的集合项的键是数字,这些值将会追加到集合的末尾:
Collection::unwrap(collect('John Doe'));
// ['John Doe']Collection::unwrap(['John Doe']);
// ['John Doe']Collection::unwrap('John Doe');
// 'John Doe'
min()
min
方法返回指定键的最小值:
$collection = collect([
10 => ['product' => 'Desk', 'price' => 200],
11 => ['product' => 'Desk', 'price' => 200]
]);
$values = $collection->values();$values->all();
/*
[
0 => ['product' => 'Desk', 'price' => 200],
1 => ['product' => 'Desk', 'price' => 200],
]
*/
mode()
mode
方法返回指定键的 众数 :
$collection = collect([1, 2, 3]);
$collection->when(true, function ($collection) {
return $collection->push(4);
});
$collection->when(false, function ($collection) {
return $collection->push(5);
});
$collection->all();
// [1, 2, 3, 4]
nth()
nth
方法创建由每隔 n 个元素组成的一个新集合:
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['michael', 'tom']
$collection = collect();$collection->whenEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['adam']
$collection = collect(['michael', 'tom']);
$collection->whenEmpty(function($collection) {
return $collection->push('adam');}, function($collection) {
return $collection->push('taylor');
});
$collection->all();
// ['michael', 'tom', 'taylor']
你可以选择传入一个偏移位置作为第二个参数:
$collection = collect(['michael', 'tom']);
$collection->whenNotEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// ['michael', 'tom', 'adam']
$collection = collect();
$collection->whenNotEmpty(function ($collection) {
return $collection->push('adam');
});
$collection->all();
// []
$collection = collect();
$collection->whenNotEmpty(function($collection) {
return $collection->push('adam');
},
function($collection) {
return $collection->push('taylor');
});
$collection->all();
// ['taylor']
only()
only
方法返回集合中所有指定键的集合项:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);$filtered->all();
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
与 only
对应的是 except 方法。
pad()
pad
方法将使用给定的值填充数组,直到数组达到指定的大小。该方法的行为与 array_pad PHP 函数功能类似。
要填充到左侧,你应该使用负值。如果给定大小的绝对值小于或等于数组的长度,则不会发生填充:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Desk', 'price' => 200],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]
*/
partition()
partition
方法可以和 PHP 函数中的 list
结合使用,用来分开通过指定条件的元素以及那些不通过指定条件的元素:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereIn('price', [150, 200]);
$filtered->all();
/*
[
['product' => 'Bookcase', 'price' => 150],
['product' => 'Desk', 'price' => 200],
]
*/
pipe()
pipe
方法将集合传给指定的回调函数并返回结果:
$collection = collect([
new User,
new User,
new Post,
]);
return $collection->whereInstanceOf(User::class);
pluck()
pluck
median
메서드는 지정된 키에 대해 을 반환합니다. 값
: $collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 80],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Pencil', 'price' => 30],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotBetween('price', [100, 200]);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 80],
['product' => 'Pencil', 'price' => 30],
]
*/
merge()
merge
메서드는 지정된 배열이나 컬렉션을 원본 컬렉션에 병합합니다. 주어진 컬렉션 항목의 문자열 키가 원본 컬렉션의 문자열 키와 일치하는 경우 지정된 컬렉션 항목의 값이 원본 컬렉션의 값을 덮어씁니다.
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->whereNotIn('price', [150, 200]);
$filtered->all();
/*
[
['product' => 'Chair', 'price' => 100],
['product' => 'Door', 'price' => 100],
]
*/
지정된 컬렉션 항목의 키가 숫자인 경우 다음과 같습니다. 값은 컬렉션 끝에 추가됩니다: $collection = Collection::wrap('John Doe');
$collection->all();
// ['John Doe']
$collection = Collection::wrap(['John Doe']);
$collection->all();
// ['John Doe']
$collection = Collection::wrap(collect('John Doe'));
$collection->all();
// ['John Doe']
🎜🎜🎜🎜🎜min ()
< /h4>🎜min
메소드는 지정된 키의 최소값을 반환합니다: 🎜$collection = collect(['Chair', 'Desk']);
$zipped = $collection->zip([100, 200]);
$zipped->all();
// [['Chair', 100], ['Desk', 200]]
🎜🎜🎜 🎜🎜mode()
🎜mode
메서드는 모드 🎜: 🎜$users = User::where('votes', '>', 500)->get();
$users->each->markAsVip();
🎜🎜🎜🎜🎜nth( )
< /h4>🎜n번째
메소드는 모든 n번째 요소로 구성된 새 세트를 생성합니다. 🎜$users = User::where('group', 'Development')->get();
return $users->sum->votes;
🎜오프셋 위치를 두 번째 매개변수로 전달하도록 선택할 수 있습니다: 🎜rrreee🎜< 이름 ="method-only">🎜🎜🎜🎜only()
🎜only
메소드 컬렉션에서 지정된 키를 가진 모든 컬렉션 항목을 반환합니다. 🎜rrreee🎜 및 only
는 excess🎜 메소드에 해당합니다. 🎜🎜🎜🎜🎜🎜pad()
🎜패드
메소드는 배열이 지정된 크기에 도달할 때까지 주어진 값으로 배열을 채웁니다. 이 방법은 array_pad🎜 PHP 함수와 유사하게 동작합니다. 🎜🎜왼쪽으로 패딩하려면 음수 값을 사용해야 합니다. 주어진 크기의 절대값이 배열 길이보다 작거나 같으면 패딩이 발생하지 않습니다: 🎜rrreee🎜🎜🎜 🎜🎜partition()
🎜partition()
메소드는 PHP의 list
와 함께 사용할 수 있습니다. 지정된 조건 요소를 통과하는 항목과 지정된 조건을 통과하지 않는 항목을 구분하는 함수: 🎜rrreee🎜🎜🎜🎜 🎜pipe() code>🎜pipe
메서드는 컬렉션을 지정된 콜백 함수에 전달하고 결과를 반환합니다. 🎜rrreee🎜🎜🎜🎜🎜pluck()
🎜pluck
메소드는 모든 값을 가져올 수 있습니다. 컬렉션의 지정된 키에 해당: 🎜rrreee🎜You 또한 생성된 세트의 키는 두 번째 인수를 전달하여 지정할 수 있습니다: 🎜rrreee🎜 중복된 키가 있는 경우 마지막으로 일치하는 요소가 팝된 세트에 삽입됩니다. : 🎜rrreee🎜🎜🎜🎜🎜🎜pop()
pop()
pop
方法从集合中移除并返回最后一个集合项:
rrreeeprepend()
prepend
方法将指定的值添加的集合的开头:
rrreee你也可以传递第二个参数来设置新增加集合项的键:
rrreeepull()
pull
方法把指定键对应的值从集合中移除并返回:
rrreeepush()
push
方法把指定的值追加到集合项的末尾:
rrreeeput()
put
方法在集合内设置给定的键值对:
rrreeerandom()
random
方法从集合中返回一个随机项:
rrreee你可以选择传入一个整数到 random
来指定要获取的随即项的数量。只要你显示传递你希望接收的数量时,则会返回项目的集合:
rrreee如果集合的项小于指定的数量,则该方法将抛出 InvalidArgumentException
。
reduce()
reduce
方法将每次迭代的结果传递给下一次迭代直到集合减少为单个值:
rrreee第一次迭代时 $carry
的数值为 null
; however,你也可以通过传入第二个参数到 reduce
来指定它的初始值:
rrreeereject()
reject
方法使用指定的回调函数过滤集合。如果回调函数返回 true
就会把对应的集合项从集合中移除:
rrreee与 reject
方法对应的是 filter
方法。
reverse()
reverse
pop
메서드는 컬렉션에서 제거하고 마지막 컬렉션 항목을 반환합니다:
rrreeeprepend()
prepend
메소드는 지정된 값을 컬렉션에 추가합니다. 시작: 🎜rrreee🎜두 번째 매개변수를 전달하여 새로 추가된 컬렉션 항목의 키를 설정할 수도 있습니다: 🎜rrreee🎜🎜🎜🎜🎜pull()
🎜pull
메서드는 컬렉션에서 지정된 키에 해당하는 값을 제거하고 다음을 반환합니다. 🎜rrreee🎜🎜🎜🎜🎜push()
🎜push
메소드 핸들 지정된 값은 컬렉션 항목의 끝에 추가됩니다: 🎜rrreee🎜🎜🎜🎜🎜 put() code>🎜put
메소드는 컬렉션 내에서 주어진 키-값 쌍을 설정합니다: 🎜rrreee🎜🎜🎜🎜🎜random()
🎜random
메서드는 컬렉션에서 무작위 항목을 반환합니다: 🎜rrreee🎜You 가져올 무작위 항목 수를 지정하는 random
에 정수를 전달하도록 선택할 수 있습니다. 받고 싶은 수량을 명시적으로 전달하는 한 항목 컬렉션이 반환됩니다. 🎜rrreee🎜 컬렉션에 지정된 항목 수보다 적은 경우 이 메서드는 InvalidArgumentException
을 발생시킵니다. 🎜🎜🎜🎜🎜🎜reduce()
🎜reduce
메소드는 세트가 단일 값으로 줄어들 때까지 각 반복의 결과를 다음 반복으로 전달합니다. 🎜rrreee🎜첫 번째 반복의 $carry
값은 null<입니다. /code >; 그러나 두 번째 매개변수를 reduce
에 전달하여 초기 값을 지정할 수도 있습니다: 🎜rrreee🎜🎜🎜🎜🎜reject()
🎜reject
메서드는 지정된 콜백 함수를 사용하여 컬렉션을 필터링합니다. 콜백 함수가 true
를 반환하면 해당 컬렉션 항목이 컬렉션에서 제거됩니다. 🎜rrreee🎜reject
메서드에 해당하는 것은 필터
🎜 메소드. 🎜🎜🎜🎜🎜🎜reverse()
🎜reverse
메소드는 컬렉션 항목의 순서를 바꾸고 원래 키를 유지하는 데 사용됩니다: 🎜rrreee🎜🎜🎜🎜🎜🎜search()
search()
search
方法在集合中搜索给定的值并返回它的键。如果没有找到,则返回 false
。
rrreee使用 「宽松」的方式进行搜索,这意味着具有整数值的字符串会被认为等于相同值的整数。使用 「严格」的方式进行搜索,就传入 true
作为该方法的第二个参数:
rrreee或者,你可以通过传递回调函数来搜索通过条件测试的第一个集合项:
rrreeeshift()
shift
方法移除并返回集合的第一个集合项:
rrreeeshuffle()
shuffle
方法随机打乱集合项:
rrreeeslice()
slice
方法返回集合中给定索引开始后面的部分:
rrreee如果你想限制返回内容的大小,可以将你期望的大小作为第二个参数传递到该方法:
rrreee默认情况下,返回的内容将会保留原始键。如果你不希望保留原始键,你可以使用 values
方法来重新建立索引。
some()
contains
方法的别名。
sort()
sort
方法对集合进行排序。排序后的集合会保留原数组的键,所以在这个例子我们将使用 values
方法去把键重置为连续编号的索引:
rrreee如果你有更高级的排序需求,可以通过自己的算法将回调函数传递到 sort
。请参阅 PHP 文档的 uasort
,这是集合的 sort
方法在底层所调用的。
{tip} 如果你需要对嵌套数组或对象进行排序,请参照 sortBy
和 sortByDesc
search
메서드는 컬렉션에서 지정된 값을 검색하고 해당 키를 반환합니다. 찾을 수 없으면 false
가 반환됩니다. rrreee
는 검색에 "완벽한" 접근 방식을 사용합니다. 즉, 정수 값이 있는 문자열은 동일한 값의 정수와 동일한 것으로 간주됩니다. "엄격한" 방식으로 검색하려면 true
를 메서드의 두 번째 매개변수로 전달하세요.
rrreee 또는 콜백 함수를 전달하여 조건 테스트 항목을 통과하는 첫 번째 컬렉션을 검색할 수도 있습니다. rrreee
🎜shift()
🎜< 코드 >shift 메소드는 컬렉션의 첫 번째 컬렉션 항목을 제거하고 반환합니다: 🎜rrreee🎜🎜🎜 🎜🎜 shuffle()
🎜shuffle
메소드는 컬렉션 항목을 무작위로 섞습니다: 🎜rrreee🎜🎜🎜🎜🎜slice()
🎜slice
메소드는 주어진 인덱스에서 시작하는 컬렉션의 일부를 반환합니다: 🎜 rrreee🎜 반환된 콘텐츠의 크기를 제한하려면 원하는 크기를 이 메서드의 두 번째 매개 변수로 전달할 수 있습니다. 🎜rrreee🎜기본적으로 반환된 콘텐츠는 원래 키를 유지합니다. 원래 키를 유지하지 않으려면 values
🎜 메서드를 사용하여 다시 색인을 생성할 수 있습니다. 🎜🎜🎜🎜🎜🎜some()
🎜contains
🎜 메소드 별칭입니다. 🎜🎜🎜🎜🎜🎜sort()
🎜sort
메소드는 컬렉션을 정렬합니다. 정렬된 컬렉션은 원래 배열의 키를 유지하므로 이 예에서는 values
🎜 메서드를 사용하여 키를 연속 번호 인덱스로 재설정합니다. 🎜rrreee🎜더 고급 정렬이 필요한 경우 자신만의 알고리즘을 사용하여 콜백 함수를 sort
에 전달할 수 있습니다. uasort
🎜에 대한 PHP 문서를 참조하세요. 이를 위해 컬렉션의 sort
메소드에 의해 하단에서 호출됩니다. 🎜🎜{tip} 중첩된 배열이나 객체를 정렬해야 하는 경우 sortBy
🎜 및 sortByDesc
🎜 메소드. 🎜🎜🎜🎜🎜🎜🎜🎜sortBy()
sortBy()
sortBy
方法将根据指定键对集合进行排序。排序后的集合会保留原始数组的键,所以在这个例子中我们使用 values
方法将键重置为连续编号的索引:
rrreee你也可以传递你自己的回调函数用于决定如何对集合的值进行排序:
rrreeesortByDesc()
该方法与 sortBy
方法一样,但是会以相反的顺序来对集合进行排序。
sortKeys()
sortKeys
方法通过底层关联数组的键来对集合进行排序:
rrreeesortKeysDesc()
该方法与 sortKeys
方法一样,但是会以相反的顺序来对集合进行排序。
splice()
splice
方法移除并返回指定索引开始的集合项片段:
rrreee你可以传递第二个参数用以限制被删除内容的大小:
rrreee此外,你可以传入含有新参数项的第三个参数来代替集合中删除的集合项:
rrreeesplit()
split
方法将集合按照给定的值拆分:
rrreeesum()
sum
方法返回集合内所有项的和:
rrreee如果集合包含嵌套数组或对象,则应该传入一个键来指定要进行求和的值:
rrreee另外,你可以传入自己的回调函数来决定要用集合中的哪些值进行求和:
rrreeetake()
take
方法返回给定数量项的新集合:
rrreee你也可以传递负整数从集合末尾获取指定数量的项:
rrreeetap()
tap
sortBy
메서드는 지정된 키를 기준으로 컬렉션을 정렬합니다. 정렬된 컬렉션은 원래 배열의 키를 유지하므로 이 예에서는 values
메서드를 사용하여 키를 연속 번호가 지정된 인덱스로 재설정합니다. rrreee 컬렉션 값을 정렬하는 방법을 결정하는 자체 콜백 함수를 전달할 수도 있습니다. rrreee
🎜🎜 sortByDesc()
🎜이 메서드는 sortBy
🎜 메서드와 동일하지만 순서가 반대입니다. 컬렉션을 정렬합니다. 🎜🎜🎜🎜🎜🎜sortKeys()
🎜sortKeys
메소드는 기본 연관 배열의 키를 기준으로 컬렉션을 정렬합니다. 🎜rrreee🎜🎜🎜🎜🎜< code>sortKeysDesc()🎜이 메서드는 sortKeys
🎜 메서드와 동일하지만 역순 정렬. 🎜🎜🎜🎜🎜🎜splice()
🎜접합
메소드는 지정된 인덱스에서 시작하는 컬렉션 항목 조각을 제거하고 반환합니다: 🎜rrreee🎜 두 번째 매개변수를 전달하여 삭제된 콘텐츠의 크기를 제한할 수 있습니다: 🎜rrreee🎜 또한 새 매개변수 항목을 전달할 수 있습니다. 컬렉션에서 삭제된 컬렉션 항목을 대체하는 세 번째 매개변수: 🎜rrreee🎜🎜🎜🎜🎜split( )
🎜split
메소드는 주어진 값에 따라 컬렉션을 분할합니다: 🎜rrreee🎜🎜🎜🎜🎜sum()
🎜sum
메서드는 집합에 있는 모든 항목의 합계를 반환합니다. 🎜rrreee🎜집합이 포함 중첩 배열 또는 객체 집합이 있는 경우 합산할 값을 지정하기 위해 키를 전달해야 합니다: 🎜rrreee🎜 또는 자체 콜백 함수를 전달하여 집합에서 어떤 값을 합산할지 결정할 수 있습니다. 요약: 🎜rrreee🎜< a name="method-take">🎜🎜🎜🎜take()
🎜< code>take 메소드는 지정된 항목 수로 새 컬렉션을 반환합니다. 🎜rrreee🎜 음의 정수를 전달하여 컬렉션 끝에서 지정된 항목 수를 가져올 수도 있습니다. 🎜rrreee🎜🎜🎜🎜🎜tap()
🎜tap
메소드 통과 주어진 콜백 함수를 컬렉션에 추가하여 특정 지점에서 컬렉션을 "탭"하고 컬렉션 자체에 영향을 주지 않고 컬렉션 항목에 대해 특정 작업을 수행할 수 있습니다. 🎜rrreee🎜🎜🎜🎜🎜🎜times()
times()
静态 times
方法通过调用给定次数的回调函数来创建新集合:
rrreee使用这个方法可以与工厂结合使用创建出 Eloquent 模型:
rrreeetoArray()
toArray
方法将集合转换成 PHP 数组
。如果集合的值是 Eloquent 模型,那也会被转换成数组:
rrreee{note} toArray
也会将所有集合的嵌套对象转换为数组。如果你想获取原数组,可以使用 all
方法。
toJson()
toJson
方法将集合转换成 JSON 字符串:
rrreeetransform()
transform
方法迭代集合并对每一个集合项调用给定的回调函数。而集合的内容也会被回调函数的返回值所取代:
rrreee{note} 与大多数集合方法不同, transform
会修改集合本身。如果你想创建新集合,可以使用 map
方法。
union()
union
方法将给定的数组添加到集合。如果给定的数组含有与原集合一样的键,则原集合的值不会被改变:
rrreeeunique()
unique
方法返回集合中所有唯一项。返回的集合保留着原数组的键,所以在这个例子中,我们使用 values
方法把键重置为连续编号的索引:
rrreee在处理嵌套数组或对象时,你可以指定用于确定唯一性的键:
rrreee你也可以通过传递自己的回调函数来确定项的唯一性:
rrreeeunique
方法在检查项目值时使用「宽松」模式比较,意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 uniqueStrict
方法做「严格」模式比较。
uniqueStrict()
这个方法与 unique
정적 times
메서드는 지정된 횟수만큼 콜백 함수를 호출하여 새 컬렉션을 생성합니다. rrreee
이 메서드를 함께 사용하세요 공장을 사용하여 Eloquent 모델 만들기: toArray()
🎜toArray
메서드는 컬렉션을 PHP 배열
로 변환합니다. 컬렉션의 값이 Eloquent 모델인 경우 해당 모델도 배열로 변환됩니다. 🎜rrreee🎜{note} toArray
는 컬렉션의 모든 중첩 객체도 배열로 변환합니다. 원본 배열을 얻으려면 all
🎜 메서드를 사용할 수 있습니다. 🎜
🎜🎜🎜🎜🎜toJson()
🎜 toJson
메서드는 컬렉션을 JSON 문자열로 변환합니다. 🎜rrreee🎜🎜🎜🎜🎜 < code>transform()🎜transform
메서드는 컬렉션을 반복하고 각 컬렉션 항목에 대해 지정된 콜백 함수를 호출합니다. 컬렉션의 내용도 콜백 함수의 반환 값으로 대체됩니다. 🎜rrreee🎜{note} 대부분의 컬렉션 방법과 달리 transform
은 컬렉션 자체를 수정합니다. 새 컬렉션을 생성하려면 map
🎜 메서드를 사용하세요. 🎜
🎜🎜🎜🎜🎜union()
🎜 union
메소드는 주어진 배열을 컬렉션에 추가합니다. 주어진 배열에 원본 컬렉션과 동일한 키가 포함되어 있으면 원본 컬렉션의 값은 변경되지 않습니다: 🎜rrreee🎜🎜🎜🎜🎜unique()
🎜unique
메서드는 컬렉션의 모든 고유 항목을 반환합니다. 반환된 컬렉션은 원래 배열의 키를 유지하므로 이 예에서는 values
🎜 메서드를 사용하여 키를 연속 번호가 지정된 인덱스로 재설정합니다. 🎜 rrreee 🎜중첩된 배열이나 객체를 처리할 때 고유성을 결정하는 데 사용되는 키를 지정할 수 있습니다. 🎜rrreee🎜또한 고유한 콜백 함수를 전달하여 항목의 고유성을 결정할 수도 있습니다. 🎜rrreee🎜unique 코드> 메서드는 항목 값을 확인할 때 "완화" 모드 비교를 사용합니다. 즉, 정수 값이 있는 문자열은 동일한 값과 동일한 정수로 처리됩니다. uniqueStrict
🎜 메서드를 사용하여 "엄격한" 모드 비교를 수행할 수 있습니다. 🎜🎜🎜🎜🎜🎜uniqueStrict()
🎜이 메서드는 < a href="#method-unique">unique
🎜와 동일합니다. 동일한 방법이지만 "strict" 모드를 사용하여 모든 값을 비교합니다. 🎜🎜🎜🎜🎜🎜🎜unless()
unless()
unless
方法当传入的第一个参数不为 true
的时候,将执行给定的回调函数:
rrreee与 unless
对应的是 when
方法。
unlessEmpty()
whenNotEmpty
方法的别名。
unlessNotEmpty()
whenEmpty
方法的别名。
unwrap()
静态 unwrap
方法返回集合内部的可用值:
rrreeevalues()
values
方法返回键被重置为连续编号的新集合:
rrreeewhen()
when
方法当传入的第一个参数为 true
时,将执行给定的回调函数:
rrreee与 when
对应的是 unless
方法。
whenEmpty()
whenEmpty
方法当集合为空时,将执行给定的回调函数:
rrreee与 whenEmpty
对应的是 whenNotEmpty
方法。
whenNotEmpty()
whenNotEmpty
方法当集合不为空时,将执行给定的回调函数:
rrreee与 whenNotEmpty
对应的是 whenEmpty
方法。
where()
where
方法通过给定的键 / 值对过滤集合:
rrreeewhere
方法在检查集合项值时使用「宽松」模式比较,这意味着具有整数值的字符串会被认为等于相同值的整数。你可以使用 whereStrict
方法进行「严格」模式比较。
whereStrict()
这个方法与 where
unless
메소드는 전달된 첫 번째 매개변수가 true
가 아닐 때 지정된 항목을 실행합니다. 콜백 함수: rrreee
및 uns
는 when
🎜unlessEmpty()
🎜whenNotEmpty
🎜 메소드의 별칭입니다. 🎜🎜🎜🎜🎜🎜unlessNotEmpty()
🎜whenEmpty
🎜 메소드의 별칭입니다. 🎜🎜🎜🎜🎜🎜unwrap()
🎜static unwrap
메소드는 컬렉션 내에서 사용 가능한 값을 반환합니다: 🎜rrreee🎜🎜🎜🎜🎜< code>values( )🎜values
메소드는 키가 연속된 숫자로 재설정된 새 컬렉션을 반환합니다. 🎜rrreee🎜🎜🎜< div name= "25703b" data-unique="25703b">🎜🎜when()
🎜when
전달된 첫 번째 매개변수가 인 경우 메소드 true
이면 지정된 콜백 함수가 실행됩니다. 🎜rrreee🎜 및 when
이 unless
🎜 메서드에 해당합니다. . 🎜🎜🎜🎜🎜🎜whenEmpty()
🎜whenEmpty
메소드는 컬렉션이 비어 있을 때 지정된 콜백 함수를 실행합니다. 🎜rrreee🎜는 whenEmpty
에 해당하고 whenNotEmpty< /code>에 해당합니다. 🎜방법. 🎜🎜🎜🎜🎜🎜whenNotEmpty()
🎜whenNotEmpty
메소드는 컬렉션이 비어 있지 않을 때 지정된 콜백 함수를 실행합니다. 🎜rrreee🎜는 whenNotEmpty
에 해당하고 whenEmpty
🎜 방법. 🎜🎜🎜🎜🎜🎜where()
🎜where
메소드는 주어진 키/값 쌍으로 컬렉션을 필터링합니다. 🎜rrreee🎜where
메소드는 컬렉션 항목 값을 확인할 때 "완화" 모드 비교를 사용합니다. 즉, 정수 값이 있는 문자열이 정수로 간주됩니다. 같은 값과 같습니다. whereStrict
🎜 메서드를 사용하여 "엄격한" 모드 비교를 수행할 수 있습니다. 🎜🎜🎜🎜🎜🎜whereStrict()
🎜이 메서드는 < a href="#method-where">where
🎜와 동일합니다. 차이점은 "엄격한" 모드 비교가 사용된다는 것입니다. 🎜🎜🎜🎜🎜🎜🎜whereBetween()
whereBetween()
whereBetween
方法会用给定的范围对集合进行过滤:
rrreeewhereIn()
whereIn
会根据包含给定数组的键 / 值对来过滤集合:
rrreeewhereIn
方法使用「宽松」的比较来检查集合项的值,这意味着具有整数值的字符串会被视为等于相同值的整数。你可以使用 whereInStrict
方法进行「严格」模式比较。
whereInStrict()
这个方法与 whereIn
方法类似;不同的是会使用「严格」模式进行比较。
whereInstanceOf()
whereInstanceOf
方法根据指定的类来过滤集合:
rrreeewhereNotBetween()
whereNotBetween
方法在指定的范围内过滤集合:
rrreeewhereNotIn()
whereNotIn
方法根据通过指定的键和不含有指定数组的值来对集合进行过滤:
rrreeewhereNotIn
方法使用「宽松」模式比较来检查集合项的值,这意味着具有整数值的字符串将被视为等于相同值的整数。你可以使用 whereNotInStrict
方法做 「严格」模式比较。
whereNotInStrict()
这个方法与 whereNotIn
方法类似;不同的是会使用 「严格」模式作比较。
wrap()
静态 wrap
方法在适当的情况下将指定的值放在集合中:
rrreeezip()
zip
whereBetween
메소드는 지정된 범위를 사용하여 컬렉션을 필터링합니다:
rrreee < div name="5b24c1" data-unique="5b24c1">
whereIn()
whereIn
은 주어진 배열을 포함하는 키를 기반으로 합니다. 값 쌍으로 컬렉션을 필터링합니다. 🎜rrreee🎜 whereIn
메서드는 "완화된" 비교를 사용하여 컬렉션 항목의 값을 확인합니다. 즉, 정수 값이 있는 문자열은 다음과 같은 정수로 처리됩니다. 같은 값. "엄격한" 모드 비교를 위해 whereInStrict
🎜 메서드를 사용할 수 있습니다. 🎜🎜🎜🎜🎜🎜whereInStrict()
🎜이 메서드는 < a href="#method-wherein">whereIn
🎜과 동일합니다. 차이점은 비교에 "엄격한" 모드가 사용된다는 것입니다. 🎜🎜🎜🎜🎜🎜whereInstanceOf()
🎜whereInstanceOf
지정된 클래스를 기반으로 컬렉션을 필터링하는 방법: 🎜rrreee🎜🎜🎜🎜🎜 whereNotBetween( )
🎜whereNotBetween
메소드는 지정된 범위 내에서 컬렉션을 필터링합니다. 🎜rrreee🎜🎜🎜🎜🎜whereNotIn()
🎜whereNotIn
메서드는 지정된 키와 해당 값을 기반으로 컬렉션을 필터링합니다. 지정된 배열을 포함하지 않습니다. 🎜rrreee🎜 whereNotIn
메서드는 "완화" 모드 비교를 사용하여 컬렉션 항목의 값을 확인합니다. 즉, 정수 값이 있는 문자열은 정수 값으로 처리됩니다. 같은 값으로. whereNotInStrict
🎜 메서드를 사용하여 "엄격한" 모드 비교를 수행할 수 있습니다. 🎜🎜🎜🎜🎜🎜whereNotInStrict()
🎜이 메서드는 < a href="#method-wherenotin">whereNotIn
🎜과 동일합니다. 비교에 "엄격한" 모드가 사용된다는 차이점이 있습니다. 🎜🎜🎜🎜🎜🎜wrap()
🎜static Wrap
메소드는 컬렉션의 적절한 위치에 지정된 값을 배치합니다: 🎜rrreee🎜🎜🎜 🎜🎜< code>zip()🎜zip
메소드는 지정된 배열의 값을 해당 인덱스에 있는 원본 컬렉션의 값과 병합합니다: 🎜rrreee🎜🎜🎜🎜🎜 🎜고급 메시징
Collection은 일반적인 작업에 대한 바로가기 모음인 "고급 메시징"도 지원합니다. 상위 수준 메시징을 지원하는 수집 방법은 average
average
, avg
, contains
, each
, every
, filter
, first
, flatMap
, groupBy
, keyBy
, map
, max
, min
, partition
, reject
, some
, sortBy
, sortByDesc
, sum
, and unique
。
每个高阶消息传递都能作为集合实例的动态的属性来访问。例如,使用 each
高阶消息传递在集合中的每个对象上调用一个方法:
rrreee同样,我们可以使用 sum
, avg
, 포함
, 첫 번째
, flatMap
🎜, groupBy
🎜, keyBy
🎜, 맵
🎜, max
🎜, 분
🎜, 파티션
🎜, 거부
🎜, 일부
🎜, sortBy
🎜, sortByDesc
🎜, sum
🎜 및 고유
🎜. 🎜🎜모든 상위 메시지 전달은 컬렉션 인스턴스의 동적 속성으로 액세스할 수 있습니다. 예를 들어 각
고차 메시징을 사용하여 컬렉션의 각 개체에 대한 메서드를 호출합니다. 🎜rrreee🎜마찬가지로 sum
고차 메시징을 사용하여 사용자를 수집할 수 있습니다. 컬렉션의 총 "투표" 수: 🎜rrreee🎜이 기사는 🎜LearnKu.com🎜 웹사이트에 처음 게시되었습니다. 🎜🎜