Laravel Lumen 數組操作


php原生:http://www.w3school.com.cn/php/php_ref_array.asp

Lumen方法:https://laravel.com/docs/5.6/helpers

Collections類方法:https://laravel.com/docs/5.6/collections https://learnku.com/docs/laravel/5.8/collections/3916

 

PHP原生

array_column()
從二維數組取對應鍵的值,組成新數組
<?php
// 表示由數據庫返回的可能記錄集的數組
$a = [
  [
    'id' => 5698,
    'first_name' => 'Bill',
    'last_name' => 'Gates',
  ],
  [
    'id' => 4767,
    'first_name' => 'Steve',
    'last_name' => 'Jobs',
  ],
  [
    'id' => 3809,
    'first_name' => 'Mark',
    'last_name' => 'Zuckerberg',
  ]
];

$last_names = array_column($a, 'last_name');
print_r($last_names);
?>

輸出

[  
  [0] => Gates
  [1] => Jobs
  [2] => Zuckerberg
]

  

array_combine()
兩個數組組成新的二維數組,其中的一個數組是鍵名,另一個數組的值為鍵值
<?php
$fname=array("Bill","Steve","Mark");
$age=array("60","56","31");

$c=array_combine($fname,$age);
print_r($c);
?>

 輸出

Array ( [Bill] => 60 [Steve] => 56 [Mark] => 31 )

  

下面是一些常用的原生函數

函數 描述
array() 創建數組。
array_change_key_case() 把數組中所有鍵更改為小寫或大寫。
array_chunk() 把一個數組分割為新的數組塊。
array_column() 返回輸入數組中某個單一列的值。
array_combine() 通過合並兩個數組來創建一個新數組。
array_count_values() 用於統計數組中所有值出現的次數。
array_diff() 比較數組,返回差集(只比較鍵值)。
array_diff_assoc() 比較數組,返回差集(比較鍵名和鍵值)。
array_diff_key() 比較數組,返回差集(只比較鍵名)。
array_diff_uassoc() 比較數組,返回差集(比較鍵名和鍵值,使用用戶自定義的鍵名比較函數)。
array_diff_ukey() 比較數組,返回差集(只比較鍵名,使用用戶自定義的鍵名比較函數)。
array_fill() 用給定的鍵值填充數組。
array_fill_keys() 用指定鍵名的給定鍵值填充數組。
array_filter() 用回調函數過濾數組中的元素。
array_flip() 交換數組中的鍵和值。
array_intersect() 比較數組,返回交集(只比較鍵值)。
array_intersect_assoc() 比較數組,返回交集(比較鍵名和鍵值)。
array_intersect_key() 比較數組,返回交集(只比較鍵名)。
array_intersect_uassoc() 比較數組,返回交集(比較鍵名和鍵值,使用用戶自定義的鍵名比較函數)。
array_intersect_ukey() 比較數組,返回交集(只比較鍵名,使用用戶自定義的鍵名比較函數)。
array_key_exists() 檢查指定的鍵名是否存在於數組中。
array_keys() 返回數組中所有的鍵名。
array_map() 把數組中的每個值發送到用戶自定義函數,返回新的值。
array_merge() 把一個或多個數組合並為一個數組。
array_merge_recursive() 遞歸地合並一個或多個數組。
array_multisort() 對多個數組或多維數組進行排序。
array_pad() 用值將數組填補到指定長度。
array_pop() 刪除數組的最后一個元素(出棧)。
array_product() 計算數組中所有值的乘積。
array_push() 將一個或多個元素插入數組的末尾(入棧)。
array_rand() 返回數組中一個或多個隨機的鍵。
array_reduce() 通過使用用戶自定義函數,以字符串返回數組。
array_replace() 使用后面數組的值替換第一個數組的值。
array_replace_recursive() 遞歸地使用后面數組的值替換第一個數組的值。
array_reverse() 以相反的順序返回數組。
array_search() 搜索數組中給定的值並返回鍵名。
array_shift() 刪除數組中首個元素,並返回被刪除元素的值。
array_slice() 返回數組中被選定的部分。
array_splice() 刪除並替換數組中指定的元素。
array_sum() 返回數組中值的和。
array_udiff() 比較數組,返回差集(只比較值,使用一個用戶自定義的鍵名比較函數)。
array_udiff_assoc() 比較數組,返回差集(比較鍵和值,使用內建函數比較鍵名,使用用戶自定義函數比較鍵值)。
array_udiff_uassoc() 比較數組,返回差集(比較鍵和值,使用兩個用戶自定義的鍵名比較函數)。
array_uintersect() 比較數組,返回交集(只比較值,使用一個用戶自定義的鍵名比較函數)。
array_uintersect_assoc() 比較數組,返回交集(比較鍵和值,使用內建函數比較鍵名,使用用戶自定義函數比較鍵值)。
array_uintersect_uassoc() 比較數組,返回交集(比較鍵和值,使用兩個用戶自定義的鍵名比較函數)。
array_unique() 刪除數組中的重復值。
array_unshift() 在數組開頭插入一個或多個元素。
array_values() 返回數組中所有的值。
array_walk() 對數組中的每個成員應用用戶函數。
array_walk_recursive() 對數組中的每個成員遞歸地應用用戶函數。
arsort() 對關聯數組按照鍵值進行降序排序。
asort() 對關聯數組按照鍵值進行升序排序。
compact() 創建包含變量名和它們的值的數組。
count() 返回數組中元素的數目。
current() 返回數組中的當前元素。
each() 返回數組中當前的鍵/值對。
end() 將數組的內部指針指向最后一個元素。
extract() 從數組中將變量導入到當前的符號表。
in_array() 檢查數組中是否存在指定的值。
key() 從關聯數組中取得鍵名。
krsort() 對數組按照鍵名逆向排序。
ksort() 對數組按照鍵名排序。
list() 把數組中的值賦給一些變量。
natcasesort() 用“自然排序”算法對數組進行不區分大小寫字母的排序。
natsort() 用“自然排序”算法對數組排序。
next() 將數組中的內部指針向前移動一位。
pos() current() 的別名。
prev() 將數組的內部指針倒回一位。
range() 創建包含指定范圍單元的數組。
reset() 將數組的內部指針指向第一個元素。
rsort() 對數組逆向排序。
shuffle() 將數組打亂。
sizeof() count() 的別名。
sort() 對數組排序。
uasort() 使用用戶自定義的比較函數對數組中的鍵值進行排序。
uksort() 使用用戶自定義的比較函數對數組中的鍵名進行排序。
usort() 使用用戶自定義的比較函數對數組進行排序。

 

Lumen方法

array_only()
取數組對應鍵的值,組成新的數組
$request = $this->request->all();//['title' => 'test', 'content' => 'test', 'name' => 'test']
$condition = array_only($request, ['title', 'content']);

 輸出

['title' => 'test', 'content' => 'test']

  

方法列表

數組和對象

array_add()

array_add如果給定的鍵在數組中不存在,則函數將給定的鍵/值對添加到數組中:

$array = array_add(['name' => 'Desk'], 'price', 100);  // ['name' => 'Desk', 'price' => 100]

 

array_collapse()

array_collapse函數將數組數組折疊為單個數組:

$array = array_collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);  // [1, 2, 3, 4, 5, 6, 7, 8, 9]

 

array_divide()

array_divide函數返回兩個數組,一個包含鍵,另一個包含給定數組的值:

[$keys, $values] = array_divide(['name' => 'Desk']);  // $keys: ['name']  // $values: ['Desk']

 

array_dot()

array_dot函數將多維數組展平為單級數組,使用“點”符號表示深度:

$array = ['products' => ['desk' => ['price' => 100]]]; $flattened = array_dot($array);  // ['products.desk.price' => 100]

 

array_except()

array_except函數從數組中刪除給定的鍵/值對:

$array = ['name' => 'Desk', 'price' => 100]; $filtered = array_except($array, ['price']);  // ['name' => 'Desk']

 

array_first()

array_first函數返回通過給定真值測試的數組的第一個元素:

$array = [100, 200, 300]; $first = array_first($array, function ($value, $key) { return $value >= 150; });  // 200

默認值也可以作為第三個參數傳遞給方法。如果沒有值通過真值測試,則返回此值:

$first = array_first($array, $callback, $default);

 

array_flatten()

array_flatten函數將多維數組展平為單個數組:

$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; $flattened = array_flatten($array);  // ['Joe', 'PHP', 'Ruby']

 

array_forget()

array_forget函數使用“點”表示法從深度嵌套的數組中刪除給定的鍵/值對:

$array = ['products' => ['desk' => ['price' => 100]]]; array_forget($array, 'products.desk');  // ['products' => []]

 

array_get()

array_get函數使用“點”表示法從深層嵌套數組中檢索值:

$array = ['products' => ['desk' => ['price' => 100]]]; $price = array_get($array, 'products.desk.price');  // 100

array_get函數還接受默認值,如果找不到特定鍵,將返回該值:

$discount = array_get($array, 'products.desk.discount', 0);  // 0

 

array_has()

array_has函數使用“點”表示法檢查數組中是否存在給定項目或項目:

$array = ['product' => ['name' => 'Desk', 'price' => 100]]; $contains = array_has($array, 'product.name');  // true $contains = array_has($array, ['product.price', 'product.discount']);  // false

 

array_last()

array_last函數返回通過給定真值測試的數組的最后一個元素:

$array = [100, 200, 300, 110]; $last = array_last($array, function ($value, $key) { return $value >= 150; });  // 300

可以將默認值作為方法的第三個參數傳遞。如果沒有值通過真值測試,則返回此值:

$last = array_last($array, $callback, $default);

 

array_only()

array_only函數僅返回給定數組中指定的鍵/值對:

$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10]; $slice = array_only($array, ['name', 'price']);  // ['name' => 'Desk', 'price' => 100]

 

array_pluck()

array_pluck函數從數組中檢索給定鍵的所有值:

$array = [ ['developer' => ['id' => 1, 'name' => 'Taylor']], ['developer' => ['id' => 2, 'name' => 'Abigail']], ]; $names = array_pluck($array, 'developer.name');  // ['Taylor', 'Abigail']

您還可以指定希望如何鍵入結果列表:

$names = array_pluck($array, 'developer.name', 'developer.id');  // [1 => 'Taylor', 2 => 'Abigail']

 

array_prepend()

array_prepend函數將項目推送到數組的開頭:

$array = ['one', 'two', 'three', 'four']; $array = array_prepend($array, 'zero');  // ['zero', 'one', 'two', 'three', 'four']

如果需要,您可以指定應該用於該值的鍵:

$array = ['price' => 100]; $array = array_prepend($array, 'Desk', 'name');  // ['name' => 'Desk', 'price' => 100]

 

array_pull()

array_pull函數返回並從數組中刪除鍵/值對:

$array = ['name' => 'Desk', 'price' => 100]; $name = array_pull($array, 'name');  // $name: Desk  // $array: ['price' => 100]

可以將默認值作為方法的第三個參數傳遞。如果密鑰不存在,將返回此值:

$value = array_pull($array, $key, $default);

 

array_random()

array_random函數從數組中返回一個隨機值:

$array = [1, 2, 3, 4, 5]; $random = array_random($array);  // 4 - (retrieved randomly)

您還可以指定要作為可選的第二個參數返回的項目數。請注意,即使只需要一個項目,提供此參數也會返回一個數組:

$items = array_random($array, 2);  // [2, 5] - (retrieved randomly)

 

array_set()

array_set函數使用“點”表示法在深層嵌套數組中設置一個值:

$array = ['products' => ['desk' => ['price' => 100]]]; array_set($array, 'products.desk.price', 200);  // ['products' => ['desk' => ['price' => 200]]]

 

array_sort()

array_sort函數按其值對數組進行排序:

$array = ['Desk', 'Table', 'Chair']; $sorted = array_sort($array);  // ['Chair', 'Desk', 'Table']

您也可以通過給定Closure的結果對數組進行排序:

$array = [ ['name' => 'Desk'], ['name' => 'Table'], ['name' => 'Chair'], ]; $sorted = array_values(array_sort($array, function ($value) { return $value['name']; })); /* [ ['name' => 'Chair'], ['name' => 'Desk'], ['name' => 'Table'], ] */

 

array_sort_recursive()

array_sort_recursive函數使用函數遞歸排序數組sort

$array = [ ['Roman', 'Taylor', 'Li'], ['PHP', 'Ruby', 'JavaScript'], ]; $sorted = array_sort_recursive($array); /* [ ['Li', 'Roman', 'Taylor'], ['JavaScript', 'PHP', 'Ruby'], ] */

 

array_where()

array_where函數使用給定的Closure過濾數組:

$array = [100, '200', 300, '400', 500]; $filtered = array_where($array, function ($value, $key) { return is_string($value); });  // [1 => '200', 3 => '400']

 

array_wrap()

array_wrap函數將給定值包裝在一個數組中。如果給定值已經是數組,則不會更改:

$string = 'Laravel'; $array = array_wrap($string);  // ['Laravel']

如果給定值為null,則返回一個空數組:

$nothing = null; $array = array_wrap($nothing);  // []

 

data_fill()

data_fill函數使用“點”表示法在嵌套數組或對象中設置缺失值:

$data = ['products' => ['desk' => ['price' => 100]]]; data_fill($data, 'products.desk.price', 200);  // ['products' => ['desk' => ['price' => 100]]] data_fill($data, 'products.desk.discount', 10);  // ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]

此函數還接受星號作為通配符,並相應地填充目標:

$data = [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2'], ], ]; data_fill($data, 'products.*.price', 200); /* [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2', 'price' => 200], ], ] */

 

data_get()

data_get函數使用“點”表示法從嵌套數組或對象中檢索值:

$data = ['products' => ['desk' => ['price' => 100]]]; $price = data_get($data, 'products.desk.price');  // 100

data_get函數還接受默認值,如果找不到指定的鍵,將返回該值:

$discount = data_get($data, 'products.desk.discount', 0);  // 0

 

data_set()

data_set函數使用“點”表示法在嵌套數組或對象中設置值:

$data = ['products' => ['desk' => ['price' => 100]]]; data_set($data, 'products.desk.price', 200);  // ['products' => ['desk' => ['price' => 200]]]

此函數還接受通配符,並相應地在目標上設置值:

$data = [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2', 'price' => 150], ], ]; data_set($data, 'products.*.price', 200); /* [ 'products' => [ ['name' => 'Desk 1', 'price' => 200], ['name' => 'Desk 2', 'price' => 200], ], ] */

默認情況下,將覆蓋任何現有值。如果您只想設置一個值,如果它不存在,您可以false作為第三個參數傳遞

$data = ['products' => ['desk' => ['price' => 100]]]; data_set($data, 'products.desk.price', 200, false);  // ['products' => ['desk' => ['price' => 100]]]

 

head()

head函數返回給定數組中的第一個元素:

$array = [100, 200, 300]; $first = head($array);  // 100

 

last()

last函數返回給定數組中的最后一個元素:

$array = [100, 200, 300]; $last = last($array);  // 300

 

 

 

all()

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

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

average()

Alias for the avg method.

avg()

The avg method returns the average value of a given key:

$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');  // 20 $average = collect([1, 1, 2, 4])->avg();  // 2

chunk()

The chunk method breaks the collection into multiple, smaller collections of a given size:

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

This method is especially useful in views when working with a grid system such as Bootstrap. Imagine you have a collection of Eloquent models you want to display in a grid:

@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()

The collapse method collapses a collection of arrays into a single, flat collection:

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

combine()

The combine method combines the keys of the collection with the values of another array or collection:

$collection = collect(['name', 'age']); $combined = $collection->combine(['George', 29]); $combined->all();  // ['name' => 'George', 'age' => 29]

concat()

The concat method appends the given array or collection values onto the end of the collection:

$collection = collect(['John Doe']); $concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']); $concatenated->all();  // ['John Doe', 'Jane Doe', 'Johnny Doe']

contains()

The contains method determines whether the collection contains a given item:

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

You may also pass a key / value pair to the contains method, which will determine if the given pair exists in the collection:

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

Finally, you may also pass a callback to the contains method to perform your own truth test:

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

The contains method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the containsStrict method to filter using "strict" comparisons.

containsStrict()

This method has the same signature as the contains method; however, all values are compared using "strict" comparisons.

count()

The count method returns the total number of items in the collection:

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

crossJoin()

The crossJoin method cross joins the collection's values among the given arrays or collections, returning a Cartesian product with all possible permutations:

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

dd()

The dd method dumps the collection's items and ends execution of the script:

$collection = collect(['John Doe', 'Jane Doe']); $collection->dd(); /* Collection { #items: array:2 [ 0 => "John Doe" 1 => "Jane Doe" ] } */

If you do not want to stop executing the script, use the dump method instead.

diff()

The diff method compares the collection against another collection or a plain PHP arraybased on its values. This method will return the values in the original collection that are not present in the given collection:

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

diffAssoc()

The diffAssoc method compares the collection against another collection or a plain PHP array based on its keys and values. This method will return the key / value pairs in the original collection that are not present in the given collection:

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

diffKeys()

The diffKeys method compares the collection against another collection or a plain PHP arraybased on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection:

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

dump()

The dump method dumps the collection's items:

$collection = collect(['John Doe', 'Jane Doe']); $collection->dump(); /* Collection { #items: array:2 [ 0 => "John Doe" 1 => "Jane Doe" ] } */

If you want to stop executing the script after dumping the collection, use the dd method instead.

each()

The each method iterates over the items in the collection and passes each item to a callback:

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

If you would like to stop iterating through the items, you may return false from your callback:

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

eachSpread()

The eachSpread method iterates over the collection's items, passing each nested item value into the given callback:

$collection = collect([['John Doe', 35], ['Jane Doe', 33]]); $collection->eachSpread(function ($name, $age) {  // });

You may stop iterating through the items by returning false from the callback:

$collection->eachSpread(function ($name, $age) { return false; });

every()

The every method may be used to verify that all elements of a collection pass a given truth test:

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

except()

The except method returns all items in the collection except for those with the specified keys:

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

For the inverse of except, see the only method.

filter()

The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:

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

If no callback is supplied, all entries of the collection that are equivalent to false will be removed:

$collection = collect([1, 2, 3, null, false, '', 0, []]); $collection->filter()->all();  // [1, 2, 3]

For the inverse of filter, see the reject method.

first()

The first method returns the first element in the collection that passes a given truth test:

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

You may also call the first method with no arguments to get the first element in the collection. If the collection is empty, null is returned:

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

firstWhere()

The firstWhere method returns the first element in the collection with the given key / value pair:

$collection = collect([ ['name' => 'Regena', 'age' => 12], ['name' => 'Linda', 'age' => 14], ['name' => 'Diego', 'age' => 23], ['name' => 'Linda', 'age' => 84], ]); $collection->firstWhere('name', 'Linda');  // ['name' => 'Linda', 'age' => 14]

You may also call the firstWhere method with an operator:

$collection->firstWhere('age', '>=', 18);  // ['name' => 'Diego', 'age' => 23]

flatMap()

The flatMap method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by a level:

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

flatten()

The flatten method flattens a multi-dimensional collection into a single dimension:

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

You may optionally pass the function a "depth" argument:

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

In this example, calling flatten without providing the depth would have also flattened the nested arrays, resulting in ['iPhone 6S''Apple''Galaxy S7''Samsung']. Providing a depth allows you to restrict the levels of nested arrays that will be flattened.

flip()

The flip method swaps the collection's keys with their corresponding values:

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

forget()

The forget method removes an item from the collection by its key:

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

 

 
Unlike most other collection methods,  forget does not return a new modified collection; it modifies the collection it is called on.

 

forPage()

The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:

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

get()

The get method returns the item at a given key. If the key does not exist, null is returned:

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

You may optionally pass a default value as the second argument:

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

You may even pass a callback as the default value. The result of the callback will be returned if the specified key does not exist:

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

groupBy()

The groupBy method groups the collection's items by a 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'], ], ] */

Instead of passing a string key, you may pass a callback. The callback should return the value you wish to key the group by:

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

Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional array:

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

has()

The has method determines if a given key exists in the collection:

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

implode()

The implode method joins the items in a collection. Its arguments depend on the type of items in the collection. If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the "glue" string you wish to place between the values:

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

If the collection contains simple strings or numeric values, pass the "glue" as the only argument to the method:

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

intersect()

The intersect method removes any values from the original collection that are not present in the given array or collection. The resulting collection will preserve the original collection's keys:

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

intersectByKeys()

The intersectByKeys method removes any keys from the original collection that are not present in the given array or collection:

$collection = collect([ 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009 ]); $intersect = $collection->intersectByKeys([ 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011 ]); $intersect->all();  // ['type' => 'screen', 'year' => 2009]

isEmpty()

The isEmpty method returns true if the collection is empty; otherwise, false is returned:

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

isNotEmpty()

The isNotEmpty method returns true if the collection is not empty; otherwise, false is returned:

collect([])->isNotEmpty();  // false

keyBy()

The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new 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'], ] */

You may also pass a callback to the method. The callback should return the value to key the collection by:

$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()

The keys method returns all of the collection's keys:

$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()

The last method returns the last element in the collection that passes a given truth test:

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

You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:

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

macro()

The static macro method allows you to add methods to the Collection class at run time. Refer to the documentation on extending collections for more information.

make()

The static make method creates a new collection instance. See the Creating Collectionssection.

map()

The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

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

 

 
Like most other collection methods,  map returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the  transform method.

 

mapInto()

The mapInto() method iterates over the collection, creating a new instance of the given class by passing the value into the constructor:

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

mapSpread()

The mapSpread method iterates over the collection's items, passing each nested item value into the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

$collection = collect([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); $chunks = $collection->chunk(2); $sequence = $chunks->mapSpread(function ($odd, $even) { return $odd + $even; }); $sequence->all();  // [1, 5, 9, 13, 17]

mapToGroups()

The mapToGroups method groups the collection's items by the given callback. The callback should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:

$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' => ['Johhny Doe'], ] */ $grouped->get('Sales')->all();  // ['John Doe', 'Jane Doe']

mapWithKeys()

The mapWithKeys method iterates through the collection and passes each value to the given callback. The callback should return an associative array containing a single key / value pair:

$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()

The max method returns the maximum value of a given key:

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

median()

The median method returns the median value of a given key:

$median = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->median('foo');  // 15 $median = collect([1, 1, 2, 4])->median();  // 1.5

merge()

The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:

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

If the given items's keys are numeric, the values will be appended to the end of the collection:

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

min()

The min method returns the minimum value of a given key:

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

mode()

The mode method returns the mode value of a given key:

$mode = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->mode('foo');  // [10] $mode = collect([1, 1, 2, 4])->mode();  // [1]

nth()

The nth method creates a new collection consisting of every n-th element:

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

You may optionally pass an offset as the second argument:

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

only()

The only method returns the items in the collection with the specified keys:

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

For the inverse of only, see the except method.

pad()

The pad method will fill the array with the given value until the array reaches the specified size. This method behaves like the array_pad PHP function.

To pad to the left, you should specify a negative size. No padding will take place if the absolute value of the given size is less than or equal to the length of the array:

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

partition()

The partition method may be combined with the list PHP function to separate elements that pass a given truth test from those that do not:

$collection = collect([1, 2, 3, 4, 5, 6]); list($underThree, $aboveThree) = $collection->partition(function ($i) { return $i < 3; }); $underThree->all();  // [1, 2] $aboveThree->all();  // [3, 4, 5, 6]

pipe()

The pipe method passes the collection to the given callback and returns the result:

$collection = collect([1, 2, 3]); $piped = $collection->pipe(function ($collection) { return $collection->sum(); });  // 6

pluck()

The pluck method retrieves all of the values for a 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 may also specify how you wish the resulting collection to be keyed:

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

If duplicate keys exist, the last matching element will be inserted into the plucked collection:

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

pop()

The pop method removes and returns the last item from the collection:

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

prepend()

The prepend method adds an 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 may also pass a second argument to set the key of the prepended item:

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

pull()

The pull method removes and returns an item from the collection by its key:

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

push()

The push method appends an item to the end of the collection:

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

put()

The put method sets 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()

The random method returns a random item from the collection:

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

You may optionally pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:

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

If the Collection has fewer items than requested, the method will throw an InvalidArgumentException.

reduce()

The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:

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

The value for $carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:

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

reject()

The reject method filters the collection using the given callback. The callback should return true if the item should be removed from the resulting collection:

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

For the inverse of the reject method, see the filter method.

reverse()

The reverse method reverses the order of the collection's items, preserving the original keys:

$collection = collect(['a', 'b', 'c', 'd', 'e']); $reversed = $collection->reverse(); $reversed->all(); /* [ 4 => 'e', 3 => 'd', 2 => 'c', 1 => 'b', 0 => 'a', ] */

search()

The search method searches the collection for the given value and returns its key if found. If the item is not found, false is returned.

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

The search is done using a "loose" comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use "strict" comparison, pass true as the second argument to the method:

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

Alternatively, you may pass in your own callback to search for the first item that passes your truth test:

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

shift()

The shift method removes and returns the first item from the collection:

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

shuffle()

The shuffle method randomly shuffles the items in the collection:

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

slice()

The slice method returns a slice of the collection starting at 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 would like to limit the size of the returned slice, pass the desired size as the second argument to the method:

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

The returned slice will preserve keys by default. If you do not wish to preserve the original keys, you can use the values method to reindex them.

sort()

The sort method sorts the collection. The sorted collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:

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

If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm. Refer to the PHP documentation on uasort, which is what the collection's sortmethod calls under the hood.

 

 
If you need to sort a collection of nested arrays or objects, see the  sortBy and  sortByDesc methods.

 

sortBy()

The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:

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

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

$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 has the same signature as the sortBy method, but will sort the collection in the opposite order.

sortKeys()

The sortKeys method sorts the collection by the keys of the underlying associative array:

$collection = collect([ 'id' => 22345, 'first' => 'John', 'last' => 'Doe', ]); $sorted = $collection->sortKeys(); $sorted->all(); /* [ 'first' => 'John', 'id' => 22345, 'last' => 'Doe', ] */

sortKeysDesc()

This method has the same signature as the sortKeys method, but will sort the collection in the opposite order.

splice()

The splice method removes and returns a slice of items starting at the specified index:

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

You may pass a second argument to limit the size of the resulting 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 a third argument containing the new items to replace the 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]

split()

The split method breaks a collection into the given number of groups:

$collection = collect([1, 2, 3, 4, 5]); $groups = $collection->split(3); $groups->toArray();  // [[1, 2], [3, 4], [5]]

sum()

The sum method returns the sum of all items in the collection:

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

If the collection contains nested arrays or objects, you should pass a key to use for determining 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 may pass your own callback to determine which values of the collection 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()

The take method returns a new collection with the specified number of items:

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

You may also pass a negative integer to take the specified amount of items from the end of the collection:

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

tap()

The tap method passes the collection to the given callback, allowing you to "tap" into the collection at a specific point and do something with the items while not affecting the collection itself:

collect([2, 4, 3, 1, 5]) ->sort() ->tap(function ($collection) { Log::debug('Values after sorting', $collection->values()->toArray()); }) ->shift();  // 1

times()

The static times method creates a new collection by invoking the callback a given amount of times:

$collection = Collection::times(10, function ($number) { return $number * 9; }); $collection->all();  // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]

This method can be useful when combined with factories to create Eloquent models:

$categories = Collection::times(3, function ($number) { return factory(Category::class)->create(['name' => 'Category #'.$number]); }); $categories->all(); /* [ ['id' => 1, 'name' => 'Category #1'], ['id' => 2, 'name' => 'Category #2'], ['id' => 3, 'name' => 'Category #3'], ] */

toArray()

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays:

$collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* [ ['name' => 'Desk', 'price' => 200], ] */

 

 
toArray also converts all of the collection's nested objects to an array. If you want to get the raw underlying array, use the  all method instead.

 

toJson()

The toJson method converts the collection into a JSON serialized string:

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

transform()

The transform method iterates over the collection and calls the given callback with each item in the collection. The items in the collection will be replaced by the values returned by the callback:

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

 

 
Unlike most other collection methods,  transform modifies the collection itself. If you wish to create a new collection instead, use the  map method.

 

union()

The union method adds the given array to the collection. If the given array contains keys that are already in the original collection, the original collection's values will be preferred:

$collection = collect([1 => ['a'], 2 => ['b']]); $union = $collection->union([3 => ['c'], 1 => ['b']]); $union->all();  // [1 => ['a'], 2 => ['b'], 3 => ['c']]

unique()

The unique method returns all of the unique items in the collection. The returned collection keeps the original array keys, so in this example we'll use the values method to reset the keys to consecutively numbered indexes:

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

When dealing with nested arrays or objects, you may 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 may also pass your own callback to determine item uniqueness:

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

The unique method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the uniqueStrict method to filter using "strict" comparisons.

uniqueStrict()

This method has the same signature as the unique method; however, all values are compared using "strict" comparisons.

unless()

The unless method will execute the given callback unless the first argument given to the method evaluates to true:

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

For the inverse of unless, see the when method.

unwrap()

The static unwrap method returns the collection's underlying items from the given value when applicable:

Collection::unwrap(collect('John Doe'));  // ['John Doe'] Collection::unwrap(['John Doe']);  // ['John Doe'] Collection::unwrap('John Doe');  // 'John Doe'

values()

The values method returns a new collection with the keys reset to consecutive integers:

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

when()

The when method will execute the given callback when the first argument given to the method evaluates to true:

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

For the inverse of when, see the unless method.

where()

The where method filters the collection by a given 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], ] */

The where method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereStrict method to filter using "strict" comparisons.

whereStrict()

This method has the same signature as the where method; however, all values are compared using "strict" comparisons.

whereIn()

The whereIn method filters the collection by a given key / value contained within the given array:

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

The whereIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereInStrict method to filter using "strict" comparisons.

whereInStrict()

This method has the same signature as the whereIn method; however, all values are compared using "strict" comparisons.

whereInstanceOf()

The whereInstanceOf method filters the collection by a given class type:

$collection = collect([ new User, new User, new Post, ]); return $collection->whereInstanceOf(User::class);

whereNotIn()

The whereNotIn method filters the collection by a given key / value not contained within the given array:

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

The whereNotIn method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the whereNotInStrict method to filter using "strict" comparisons.

whereNotInStrict()

This method has the same signature as the whereNotIn method; however, all values are compared using "strict" comparisons.

wrap()

The static wrap method wraps the given value in a collection when applicable:

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

zip()

The zip method merges together the values of the given array with the values of the original collection at the corresponding index:

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

Higher Order Messages

Collections also provide support for "higher order messages", which are short-cuts for performing common actions on collections. The collection methods that provide higher order messages are: averageavgcontainseacheveryfilterfirstflatMapgroupBykeyBymapmaxminpartitionrejectsortBysortByDescsum, and unique.

Each higher order message can be accessed as a dynamic property on a collection instance. For instance, let's use the each higher order message to call a method on each object within a collection:

$users = User::where('votes', '>', 500)->get(); $users->each->markAsVip();

Likewise, we can use the sum higher order message to gather the total number of "votes" for a collection of users:

$users = User::where('group', 'Development')->get(); return $users->sum->votes;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM