aggregate


1. Introduction

Illuminate\Support\Collection Class provides a smooth and convenient encapsulation for processing array data. For example, looking at the following code, we use auxiliary functions collect Create a new collection instance and run it for each element strtoupper Function, and then remove all empty elements:

 $collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); });

As you can see, Collection Class allows you to use the method chain to perform matching and reducing operations on the underlying array. Usually, no Collection Method will return a new Collection example.

2. Create Collection

As mentioned above, auxiliary functions collect Returns a new Illuminate\Support\Collection Therefore, creating a collection is simple:

 $collection = collect([1, 2, 3]);

By default, Eloquent model The collection of always returns Collection Instance. In addition, no matter where it is, any method can be used freely Collection Class.

3. Set method

In the next part of this document, we will discuss Collection For each valid method on the class, all these methods can operate on the underlying array smoothly in the way of method chain. In addition, almost every method returns a new Collection Instance allows you to keep the original collection backup when necessary.

all()

all The method simply returns the underlying array represented by the collection:

 collect([1, 2, 3])->all(); // [1, 2, 3]

avg()

The avg method returns the average value of all set items:

 collect([1, 2, 3, 4, 5])->avg(); // 3

If the collection contains nested arrays or objects, you need to specify the key to use to determine the average value of those values:

 $collection = collect([ ['name' => 'JavaScript: The Good Parts', 'pages' => 176], ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],]); $collection->avg('pages'); // 636

chunk()

chunk Method To divide a set into multiple small sets of small size:

 $collection = collect([1, 2, 3, 4, 5, 6, 7]); $chunks = $collection->chunk(4); $chunks->toArray(); // [[1, 2, 3, 4], [5, 6, 7]]

When dealing with fence systems such as Bootstrap When the method is view It is especially useful to build a Eloquent Model collection:

 @foreach ($products->chunk(3) as $chunk) <div class="row"> @foreach ($chunk as $product) <div class="col-xs-4">{{ $product->name }}</div> @endforeach </div> @endforeach

collapse()

collapse Method to shrink a multidimensional array collection into a one-dimensional array:

 $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]

contains()

contains Method to determine whether a set contains a given item:

 $collection = collect(['name' => 'Desk', 'price' => 100]); $collection->contains('Desk'); // true $collection->contains('New York'); // false

You can also pass a key value pair to contains Method, which will determine whether the given key value pair exists in the collection:

 $collection = collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ]); $collection->contains('product', 'Bookcase'); // false

Finally, you can also send a callback to contains Method to perform your own real-world tests:

 $collection = collect([1, 2, 3, 4, 5]); $collection->contains(function ($key, $value) { return $value > 5; }); // false

count()

count Method returns the number of all items in the collection:

 $collection = collect([1, 2, 3, 4]); $collection->count(); // 4

diff()

diff Method to compare a collection with another collection or a native PHP array:

 $collection = collect([1, 2, 3, 4, 5]); $diff = $collection->diff([2, 4, 6, 8]); $diff->all(); // [1, 3, 5]

each()

each Method iterates over data items in the collection and passes each data item to the given callback:

 $collection = $collection->each(function ($item, $key) { // });

Callback return false The cycle will be terminated:

 $collection = $collection->each(function ($item, $key) { if (/* some condition */) { return false; } });

every()

every Method to create an array containing n-th New collection of elements:

 $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->every(4); // ['a', 'e']

You can also choose to specify which element to start from:

 $collection->every(4, 1); // ['b', 'f']

except()

except Method returns all collection items in the collection except the specified key:

 $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]); $filtered = $collection->except(['price', 'discount']); $filtered->all(); // ['product_id' => 1, 'name' => 'Desk']

And except In contrast only method.

filter()

filter The method filters the collection through a given callback. Only the data items that pass the given test will remain:

 $collection = collect([1, 2, 3, 4]); $filtered = $collection->filter(function ($item) { return $item > 2; }); $filtered->all(); // [3, 4]

and filter The relative method is reject

first()

first Method returns the first element of the test collection that passed:

 collect([1, 2, 3, 4])->first(function ($key, $value) { return $value > 2; }); // 3

You can also call the first Method to get the first element of the collection. If the collection is empty, null is returned:

 collect([1, 2, 3, 4])->first(); // 1

flatten()

flatten The method changes a multi-dimensional set into a one-dimensional set:

 $collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]); $flattened = $collection->flatten(); $flattened->all(); // ['taylor', 'php', 'javascript'];

flip()

flip Method to exchange the key values of the collection:

 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $flipped = $collection->flip(); $flipped->all(); // ['taylor' => 'name', 'laravel' => 'framework']

forget()

forget Method to remove data items from a collection by key:

 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $collection->forget('name'); $collection->all(); // [framework' => 'laravel']
Note: Unlike most collection methods, forget Do not return the new modified set; It only modifies the called collection.

forPage()

forPage Method returns a new set containing data items of the given number of pages:

 $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->forPage(2, 3); $collection->all(); // [4, 5, 6]

This method requires the number of pages passed in and the number of displays per page parameters.

get()

get Method returns the data item of the given key. If it does not exist, null is returned:

 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('name'); // taylor

You can choose to pass the default value as the second parameter:

 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('foo', 'default-value'); // default-value

You can even pass a callback as the default value. If the given key does not exist, the callback result will return:

 $collection->get('email', function () { return 'default-value';}); // default-value

groupBy()

groupBy Method to group collection data items by given key:

 $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'], ], ] */

In addition to passing the string key, a callback can also be passed. The callback should return the grouped value:

 $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'], ], ] */

has()

has Method to determine whether the given key exists in the set:

 $collection = collect(['account_id' => 1, 'product' => 'Desk']); $collection->has('email'); // false

implode()

implode Method to connect data items in a collection. Its parameters depend on the type of data item in the collection.

If the collection contains arrays or objects, you should pass the attribute keys you want to connect and the "glue" string you want to put between values:

 $collection = collect([ ['account_id' => 1, 'product' => 'Desk'], ['account_id' => 2, 'product' => 'Chair'], ]); $collection->implode('product', ', '); // Desk, Chair

If the collection contains a simple string or numeric value, just pass the "glue" string as the only parameter to the method:

 collect([1, 2, 3, 4, 5])->implode('-'); // '1-2-3-4-5'

intersect()

intersect Method returns the intersection of two sets:

 $collection = collect(['Desk', 'Sofa', 'Chair']); $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']); $intersect->all(); // [0 => 'Desk', 2 => 'Chair']

As you can see, the result set only keeps the keys of the original set.

isEmpty()

If the collection is empty isEmpty Method return true Otherwise, return false

 collect([])->isEmpty(); // true

keyBy()

Use the value of the specified key as the key of the collection:

 $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'], ] */

If multiple data items have the same key, only the last one will appear in the new set.

You can pass your callback and return the processed key value as a new key:

 $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'], ] */

keys()

keys Method returns the keys of all collections:

 $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']

last()

last Method returns the last element of the collection that passed the test:

 collect([1, 2, 3, 4])->last(function ($key, $value) { return $value < 3; }); // 2

You can also call parameterless last Method to get the last element of the collection. If the collection is empty. Return null:

 collect([1, 2, 3, 4])->last(); // 4

map()

map Method traverses the set and passes each value to the given callback. This callback can modify the data item and return, thus generating a new modified collection:

 $collection = collect([1, 2, 3, 4, 5]); $multiplied = $collection->map(function ($item, $key) { return $item * 2; }); $multiplied->all(); // [2, 4, 6, 8, 10]

Note: Like most collection methods, map Return a new collection instance; It does not modify the instance being called. If you want to change the original collection, use transform method.

max()

max Method returns the maximum value in the collection:

 $max = collect([['foo' => 10], ['foo' => 20]])->max('foo'); // 20 $max = collect([1, 2, 3, 4, 5])->max(); // 5

merge()

merge Method to merge the given array into a collection. Any string key in the array that matches the string key in the collection will overwrite the value in the collection:

 $collection = collect(['product_id' => 1, 'name' => 'Desk']); $merged = $collection->merge(['price' => 100, 'discount' => false]); $merged->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]

If the key of a given array is a number, the value of the array will be appended to the collection:

 $collection = collect(['Desk', 'Chair']); $merged = $collection->merge(['Bookcase', 'Door']); $merged->all(); // ['Desk', 'Chair', 'Bookcase', 'Door']

min()

min Method returns the minimum value in the collection:

 $min = collect([['foo' => 10], ['foo' => 20]])->min('foo'); // 10 $min = collect([1, 2, 3, 4, 5])->min(); // 1

only()

only Method returns the collection item of the specified key in the collection:

 $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]); $filtered = $collection->only(['product_id', 'name']); $filtered->all(); // ['product_id' => 1, 'name' => 'Desk']

And only The relative method is except method.

pluck()

pluck Method gets all set values for the given key:

 $collection = collect([ ['product_id' => 'prod-100', 'name' => 'Desk'], ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $plucked = $collection->pluck('name'); $plucked->all(); // ['Desk', 'Chair']

You can also specify how you want the result set to set keys:

 $plucked = $collection->pluck('name', 'product_id'); $plucked->all(); // ['prod-100' => 'Desk', 'prod-200' => 'Chair']

pop()

pop Method to remove and return the last data item in the collection:

 $collection = collect([1, 2, 3, 4, 5]); $collection->pop(); // 5 $collection->all(); // [1, 2, 3, 4]

prepend()

prepend Method to add a data item to the beginning of the collection:

 $collection = collect([1, 2, 3, 4, 5]); $collection->prepend(0); $collection->all(); // [0, 1, 2, 3, 4, 5]

You can also pass the second parameter to the key used to set the predecessor:

 $collection = collect(['one' => 1, 'two', => 2]); $collection->prepend(0, 'zero'); $collection->all(); // ['zero' => 0, 'one' => 1, 'two', => 2]

pull()

pull Method removes the data item from the collection by key and returns it:

 $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']); $collection->pull('name'); // 'Desk' $collection->all(); // ['product_id' => 'prod-100']

push()

push Method appends data items to the end of the set:

 $collection = collect([1, 2, 3, 4]); $collection->push(5); $collection->all(); // [1, 2, 3, 4, 5]

put()

put Method to set the given key and value in the collection:

 $collection = collect(['product_id' => 1, 'name' => 'Desk']); $collection->put('price', 100); $collection->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

random()

random Method returns random data items from a collection:

 $collection = collect([1, 2, 3, 4, 5]); $collection->random(); // 4 - (retrieved randomly)

You can pass an integer data to random Function, if the integer value is greater than 1, it will return a set:

 $random = $collection->random(3); $random->all(); // [2, 4, 5] - (retrieved randomly)

reduce()

reduce The method is used to reduce the collection to a single value and pass the results of each iteration to subsequent iterations:

 $collection = collect([1, 2, 3]); $total = $collection->reduce(function ($carry, $item) { return $carry + $item; }); // 6

At the first iteration $carry The value of is null; However, you can pass the second parameter to reduce To specify its initial value:

 $collection->reduce(function ($carry, $item) { return $carry + $item; }, 4); // 10

reject()

reject Method filters the collection using the given callback, which should return all data items it wants to remove from the result collection true

 $collection = collect([1, 2, 3, 4]); $filtered = $collection->reject(function ($item) { return $item > 2; }); $filtered->all(); // [1, 2]

and reduce The relative method is filter method.

reverse()

reverse Method reverses the order of set data items:

 $collection = collect([1, 2, 3, 4, 5]); $reversed = $collection->reverse(); $reversed->all(); // [5, 4, 3, 2, 1]

search()

search The method queries the set for the given value, returns the corresponding key if it is found, or returns the key if it is not found false

 $collection = collect([2, 4, 6, 8]); $collection->search(4); // 1

The above search uses loose comparison, and strict comparison should be used to pass true As the second parameter to this method:

 $collection->search('4', true); // false

In addition, you can also pass your own callback to search the first data item that passed the test:

 $collection->search(function ($item, $key) { return $item > 5;}); // 2

shift()

shift Method to remove from the collection and return the first data item:

 $collection = collect([1, 2, 3, 4, 5]); $collection->shift(); // 1 $collection->all(); // [2, 3, 4, 5]

shuffle()

shuffle Method: Randomly scramble the data items in the set:

 $collection = collect([1, 2, 3, 4, 5]); $shuffled = $collection->shuffle(); $shuffled->all(); // [3, 2, 5, 1, 4] // (generated randomly)

slice()

slice Method returns a slice of the set from the given index:

 $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $slice = $collection->slice(4); $slice->all(); // [5, 6, 7, 8, 9, 10]

If you want to limit the size of the returned slice, pass the size value to the method as the second parameter:

 $slice = $collection->slice(4, 2); $slice->all(); // [5, 6]

The returned slice has a new, digitally indexed key. If you want to keep the original key, you can pass the third parameter true To this method.

sort()

sort Method to sort the collection:

 $collection = collect([5, 3, 1, 2, 4]); $sorted = $collection->sort(); $sorted->values()->all(); // [1, 2, 3, 4, 5]

The sorted collection keeps the original array key. In this example, we use values Method reset key to consecutive numbered index.

To sort nested collections and objects, view sortBy And sortByDesc method.

If you need more advanced sorting, you can use your own algorithm to send a callback to sort method. Refer to the official PHP documentation about usort Description of, sort The method is called at the bottom of the method.

sortBy()

sortBy Method to sort the collection by the given key:

 $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], ] */

The sorted collection keeps the original array index. In this example, use values Method to reset the key to a continuous index.

You can also pass your own callback to determine how to sort the values of the collection:

 $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']], ] */

sortByDesc()

This method and sortBy The usage is the same, but the difference is that they are sorted in reverse order.

splice()

splice The method removes from the given location and returns the data item slice:

 $collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2); $chunk->all(); // [3, 4, 5] $collection->all(); // [1, 2]

You can pass parameters to limit the size of the returned chunk:

 $collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2, 1); $chunk->all(); // [3] $collection->all(); // [1, 2, 4, 5]

In addition, you can pass the third parameter to include new data items to replace the data items removed from the collection:

 $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]

sum()

sum Method returns the sum of all data items in the collection:

 collect([1, 2, 3, 4, 5])->sum(); // 15

If the collection contains nested arrays or objects, a key should be passed to determine which values to sum:

 $collection = collect([ ['name' => 'JavaScript: The Good Parts', 'pages' => 176], ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096], ]); $collection->sum('pages'); // 1272

In addition, you can also pass your own callback to determine which values to sum:

 $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

take()

take Method returns a new collection using the specified number of data items:

 $collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(3); $chunk->all(); // [0, 1, 2]

You can also pass negative numbers to get the specified number of data items from the end of the set:

 $collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(-2); $chunk->all(); // [4, 5]

toArray()

toArray Method to convert the collection into a native PHP array. If the value of the collection is an Eloquent model, the model will also be converted into an array:

 $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* [ ['name' => 'Desk', 'price' => 200], ] */
be careful: toArray All nested objects are also converted to arrays. If you want to get the underlying array, use all method.

toJson()

toJson Method to convert the collection into JSON:

 $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toJson(); // '{"name":"Desk","price":200}'

transform()

transform Method iterates over the collection and calls the given callback for each data item in the collection. The data items in the collection will be replaced with the values returned from the callback:

 $collection = collect([1, 2, 3, 4, 5]); $collection->transform(function ($item, $key) { return $item * 2; }); $collection->all(); // [2, 4, 6, 8, 10]

Note: Unlike most other set methods, transform Modify the collection itself. If you want to create a new collection, use map method.

unique()

unique Method returns all unique data items in the collection:

 $collection = collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4]

The returned set keeps the original array key. In this example, we use values Method to reset these keys to consecutive numeric indexes.

When processing nested arrays or objects, you can specify the key used to determine uniqueness:

 $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'], ] */

You can also specify your own callback to judge the uniqueness of data items:

 $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'], ] */

values()

values Method returns a new set using the key reset to a continuous integer number:

 $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], ] */

where()

where Method filters the collection by giving a key value pair:

 $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], ] */

When checking data item values where Methods Use strict constraints. use whereLoose Method to filter loose constraints.

whereLoose()

This method and where The use method is the same, but the difference is that whereLoose Use loose constraints when comparing values.

zip()

zip The method is to merge the values of the given array at the corresponding index of the values of the collection:

 $collection = collect(['Chair', 'Desk']); $zipped = $collection->zip([100, 200]); $zipped->all(); // [['Chair', 100], ['Desk', 200]]

give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: cache

>>Next: Integrated front-end resource: Laravel Elixir