## Laravel学习笔记汇总——Collection方法详解
本文参考:https:// laravel.com/docs/8.x/collections
// 返回整个底层的数组 collect([1, 2, 3])->all();? // [1, 2, 3]
// 返回平均数 $average = collect([1, 1, 2, 4])->avg(); # 也可以用全拼average // 2
// 对某个字段值作平均,如果某项中不存在该字段值,则不计入 $average = collect([ ? ? ['foo' => 10], ? ? ['foo' => 10], ? ? ['foo' => 20], ? ? ['foo' => 40] ])->avg('foo'); // 20
// 将原Collection拆分成一定大小的几部分 $collection = collect([1, 2, 3, 4, 5, 6, 7]); $chunks = $collection->chunk(4); $chunks->all(); // [[1, 2, 3, 4], [5, 6, 7]]
// chunkWhile 的神奇用法,使用一个函数作为chunk的条件 $collection = collect(str_split('AABBCCCD')); $chunks = $collection->chunkWhile(function ($value, $key, $chunk) { ? ? return $value === $chunk->last(); }); $chunks->all(); // [['A', 'A'], ['B', 'B'], ['C', 'C', 'C'], ['D']]
// collapse用于让数组的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将一个数组作为键,第二个数组作为值,生成关联数组 $collection = collect(['name', 'age']); $combined = $collection->combine(['George', 29]); $combined->all(); // ['name' => 'George', 'age' => 29]
// concat将多个部分合成一个数组 $collection = collect(['John Doe']); $concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']); $concatenated->all(); // ['John Doe', 'Jane Doe', 'Johnny Doe']
// contains将检测数组中是否存在某个值 $collection = collect(['name' => 'Desk', 'price' => 100]); $collection->contains('Desk');// true $collection->contains('New York');// false
// 如果参数是回调函数则判断是否存在满足函数返回true的值 $collection = collect([1, 2, 3, 4, 5]); $collection->contains(function ($value, $key) { ? ? return $value > 5; }); // false
// 如果参数是key/value对,则判断是否存在数组中存在该键值对 $collection = collect([ ? ? ['product' => 'Desk', 'price' => 200], ? ? ['product' => 'Chair', 'price' => 100], ]); $collection->contains('product', 'Bookcase'); // false
// contain判断是否等值时用的是不严格比较法,如果要使用严格比较判断,需要改用containStrict
// count可以返回数组的个数 $collection = collect([1, 2, 3, 4]); $collection->count(); // 4
// countBy可以返回数组中每种值出现的次数 $collection = collect([1, 2, 2, 2, 3]); $counted = $collection->countBy(); $counted->all(); // [1 => 1, 2 => 3, 3 => 1]
// countBy也可以用回调函数作为参数,此时统计回调函数返回值的个数情况 $collection = collect(['alice@gmail.com', 'bob@yahoo.com', 'carlos@gmail.com']); $counted = $collection->countBy(function ($email) { ? ? return substr(strrchr($email, "@"), 1); }); $counted->all(); // ['gmail.com' => 2, 'yahoo.com' => 1]
// crossJoin返回笛卡尔积;当参数个数为2个时,返回三个数组的笛卡尔积 $collection = collect([1, 2]); $matrix = $collection->crossJoin(['a', 'b']); $matrix->all(); /* ? ? [ ? ? ? ? [1, 'a'], ? ? ? ? [1, 'b'], ? ? ? ? [2, 'a'], ? ? ? ? [2, 'b'], ? ? ] */
// diff得到A数组不在B数组中的元素 $collection = collect([1, 2, 3, 4, 5]); $diff = $collection->diff([2, 4, 6, 8]); $diff->all(); // [1, 3, 5]
// diffAssoc是diff的关联数组版本,比较的是键值对,值不同也算不在B中 $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只看A中的键在不在B中,如果不在就放到结果中 $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]
// duplicates返回数组中重复的元素位置及元素值 $collection = collect(['a', 'b', 'a', 'c', 'b']); $collection->duplicates(); // [2 => 'a', 4 => 'b']
// 对关联数组可以指定key,判断是否是重复值 $employees = collect([ ? ? ['email' => 'abigail@example.com', 'position' => 'Developer'], ? ? ['email' => 'james@example.com', 'position' => 'Designer'], ? ? ['email' => 'victoria@example.com', 'position' => 'Developer'], ]); $employees->duplicates('position'); // [2 => 'Developer']
// duplicatesStrict是duplicates的严格比较版,使用方法相同
// each对每一个元素进行迭代,如想中断,则返回false $collection->each(function ($item, $key) { ? ? if (/* condition */) { ? ? ? ? return false; ? ? } });
// every对所有元素进行判断,都满足参数中的回调函数时整体返回true,否则为false。当数组为空时,总返回true。 $result = collect([1, 2, 3, 4])->every(function ($value, $key) { ? ? return $value > 2; }); echo $result; // false
// except将排除指定的键(字段),only则只要某个键 $collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]); $filtered = $collection->except(['price', 'discount']); $filtered->all(); // ['product_id' => 1]
// filter将按回调函数返回值情况,过滤出一批元素;与reject功能相对 $collection = collect([1, 2, 3, 4]); $filtered = $collection->filter(function ($value, $key) { ? ? return $value > 2; }); $filtered->all(); // [3, 4]
// 如果filter不带回调函数,则原数组中相当于false的值将被过滤掉 $collection = collect([1, 2, 3, null, false, '', 0, []]); $collection->filter()->all(); // [1, 2, 3]
// first返回数组的第一个元素;如果里面带回调函数参数,则返回第一个能让函数返回true的元素 collect([1, 2, 3, 4])->first(); // 1 collect([1, 2, 3, 4])->first(function ($value, $key) { ? ? return $value > 2; }); // 3
// 使用last得到最后一行记录,也可以使用回调函数作为参数 collect([1, 2, 3, 4])->last(); // 4
// firstWhere 会对数组中元素的键值作限制 $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] // 使用比较运算符也可以 $collection->firstWhere('age', '>=', 18); // ['name' => 'Diego', 'age' => 23]
// flapMap 遍历元素并将每一元素值用回调函数处理,返回一个新的一维数组 $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把多维数组压缩成一维 $collection = collect([ ? ? 'name' => 'taylor', ? ? 'languages' => [ ? ? ? ? 'php', 'javascript' ? ? ] ]); $flattened = $collection->flatten(); $flattened->all(); // ['taylor', 'php', 'javascript'];
// flatten对高维数组也可以带上参数如1,指只压缩掉第一维 $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'], ? ? ] */
// flip可以将关联数组的键值对调 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $flipped = $collection->flip(); $flipped->all(); // ['taylor' => 'name', 'laravel' => 'framework']
// forget将相应的键去除,直接在原Collection上修改 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $collection->forget('name'); $collection->all(); // ['framework' => 'laravel']
// forPage将数组分页,并得到某一页的数据 $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]); $chunk = $collection->forPage(2, 3); // 每3个元素为一页,取第2页的元素 $chunk->all(); // [4, 5, 6]
// get返回指定键的值 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('name'); // taylor
// get可以有第二个参数,表示该键不存在时,使用默认值 $collection = collect(['name' => 'taylor', 'framework' => 'laravel']); $value = $collection->get('age', 34); // 34
// 使用groupBy可以对数组分组 $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->all(); /* ? ? [ ? ? ? ? 'account-x10' => [ ? ? ? ? ? ? ['account_id' => 'account-x10', 'product' => 'Chair'], ? ? ? ? ? ? ['account_id' => 'account-x10', 'product' => 'Bookcase'], ? ? ? ? ], ? ? ? ? 'account-x11' => [ ? ? ? ? ? ? ['account_id' => 'account-x11', 'product' => 'Desk'], ? ? ? ? ], ? ? ] */
// has用于判断数组中是否有给定的键 $collection = collect(['account_id' => 1, 'product' => 'Desk', 'amount' => 5]); $collection->has('product');// true $collection->has(['product', 'amount']);// true $collection->has(['amount', 'price']);// false
// implode用于将数组连接成字符串 collect([1, 2, 3, 4, 5])->implode('-'); // '1-2-3-4-5'
// 如果数组里面的元素是数组或对象,则需要提供一个键名 $collection = collect([ ? ? ['account_id' => 1, 'product' => 'Desk'], ? ? ['account_id' => 2, 'product' => 'Chair'], ]); $collection->implode('product', ', '); // Desk, Chair
// intersect求两数组的交集 $collection = collect(['Desk', 'Sofa', 'Chair']); $intersect = $collection->intersect(['Desk', 'Chair', 'Bookcase']); $intersect->all(); // [0 => 'Desk', 2 => 'Chair']
// intersectByKeys得到两关联数组中键名存在交集的部分 $collection = collect([ ? ? 'serial' => 'UX301', 'type' => 'screen', 'year' => 2009, ]); $intersect = $collection->intersectByKeys([ ? ? 'reference' => 'UX404', 'type' => 'tab', 'year' => 2011, ]); $intersect->all(); // ['type' => 'screen', 'year' => 2009]
// isEmpty判断一个Collection中的数组是否为空 collect([])->isEmpty(); // true // isNotEmpty判断一个Collection中的数组是否不为空 collect([])->isNotEmpty(); // false
// join连接数组元素,第二个可选参数可以指定最后两个元素中间的连接符 collect(['a', 'b', 'c'])->join(', '); // 'a, b, c' collect(['a', 'b', 'c'])->join(', ', ', and '); // 'a, b, and c' collect(['a', 'b'])->join(', ', ' and '); // 'a and b' collect(['a'])->join(', ', ' and '); // 'a' collect([])->join(', ', ' and '); // ''
// keyBy将collection中的关联数组元素,按指定的key创建新的数组,key相同的只用最后一条记录 $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'], ? ? ] */
// keys返回所有元素的key $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']
// map可以对所有元素进行映射操作,返回一个新的collection $collection = collect([1, 2, 3, 4, 5]); $multiplied = $collection->map(function ($item, $key) { ? ? return $item * 2; }); $multiplied->all(); // [2, 4, 6, 8, 10]
// mapInto将集合的元素映射作为类的构造函数参数,得到新的类实例 // 将类和回调函数作为映射参数都是一种以数据为中心的思路 class Currency { ? ? 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可以将数组型的数据项作为元素传入回调函数,作进一步计算处理 $collection = collect([[0, 1, 2], [3, 4, 5], [6, 7, 8]]); $sequence = $collection->mapSpread(function ($first, $second, $third) { ? ? return $first+$second+$third; }); $sequence->all(); // [3,12,21]
// mapToGroup得到回调函数中规定键值对的数据,如有重复会将所有同一键的内容放到数组中 $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->all(); /* ? ? [ ? ? ? ? 'Sales' => ['John Doe', 'Jane Doe'], ? ? ? ? 'Marketing' => ['Johnny Doe'], ? ? ] */
// mapWithKeys得到回调函数中规定键值对的数据,如有重复只保留最后一条记录 $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返回数组中的最大值,可以带一个参数表示指定哪一个字段 // median, min, mode等与之相同 $max = collect([ ? ? ['foo' => 10], ? ? ['foo' => 20] ])->max('foo'); // 20 $max = collect([1, 2, 3, 4, 5])->max(); // 5
// merge会直接合并两个普通数组 $collection = collect(['Desk', 'Chair']); $merged = $collection->merge(['Bookcase', 'Door']); $merged->all(); // ['Desk', 'Chair', 'Bookcase', 'Door']
// merge合并两个关联数组,如果提供的新数组中有键与原数组重复,值取新数组中的 $collection = collect(['product_id' => 1, 'price' => 100]); $merged = $collection->merge(['price' => 200, 'discount' => false]); $merged->all(); // ['product_id' => 1, 'price' => 200, 'discount' => false]
// mergeRecursive会将两个关联数组中相同键的值合并为一个普通数组 $collection = collect(['product_id' => 1, 'price' => 100]); $merged = $collection->mergeRecursive([ ? ? 'product_id' => 2, ? ? 'price' => 200, ? ? 'discount' => false ]); $merged->all(); // ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]
// nth从第0个元素起,每n个元素放入结果中 $collection = collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e'] // 第2个参数可以指定从哪一索引位开始 $collection->nth(4, 1); // ['b', 'f']
// pad让数组用第二个参数填充到n个元素 $collection = collect(['A', 'B', 'C']); $filtered = $collection->pad(5, 0); $filtered->all(); // ['A', 'B', 'C', 0, 0] // 如果n为负数,则表示在左边填充 $filtered = $collection->pad(-5, 0); $filtered->all(); // [0, 0, 'A', 'B', 'C']
// partition将原数组分为通过和未通过回调函数测试的两大部分 $collection = collect([1, 2, 3, 4, 5, 6]); [$underThree, $equalOrAboveThree] = $collection->partition(function ($i) { ? ? return $i < 3; }); $underThree->all(); // [1, 2] $equalOrAboveThree->all(); // [3, 4, 5, 6]
// pipe $collection = collect([ ?? ?['name' => 'News', 'view' => 100 ], ?? ?['name' => 'Sports', 'view' => 800 ], ?? ?['name' => 'Travel', 'view' => 600 ], ?? ?['name' => 'Culture', 'view' => 300 ], ?? ?['name' => 'Science', 'view' => 1000 ], ]); $piped = $collection->pipe(function ($collection) { ?? ?return [ ?? ?'sum' => $collection->sum('view'), ?? ?'max' => $collection->max('view'), ?? ?'min' => $collection->min('view'), ?? ?// 按是否包含t分为两组 ?? ?'partition' => $collection->partition(function($item){ ?? ??? ?return stristr($item['name'], 't'); ?? ?}), ?? ?]; });
// pipeInto将数据导入一个类实例 class ResourceCollection { ? ? public $collection;
? ? public function __construct(Collection $collection) ? ? { ? ? ? ? $this->collection = $collection; ? ? } }
$collection = collect([1, 2, 3]); $resource = $collection->pipeInto(ResourceCollection::class); $resource->collection->all(); // [1, 2, 3]
// pluck获取一个字段的所有值 $collection = collect([ ? ? ['product_id' => 'prod-100', 'name' => 'Desk'], ? ? ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $plucked = $collection->pluck('name'); $plucked->all(); // ['Desk', 'Chair']
// pluck如果有第二个参数,则表示返回以第二个参数为键,第一个参数为值的关联数组 $plucked = $collection->pluck('name', 'product_id'); $plucked->all(); // ['prod-100' => 'Desk', 'prod-200' => 'Chair']
// pop删除collection中最后一个元素,并返回它;直接修改原数据 $collection = collect([1, 2, 3, 4, 5]); $collection->pop();// 5 $collection->all(); // [1, 2, 3, 4]
// prepend在collection的前面添加一个元素;直接修改原数据 $collection = collect([1, 2, 3, 4, 5]); $collection->prepend(0); $collection->all(); // [0, 1, 2, 3, 4, 5]
// 如果指定了第二个参数,则将以第二个参数为index/key $collection = collect(['one' => 1, 'two' => 2]); $collection->prepend(0, 'zero'); $collection->all(); // ['zero' => 0, 'one' => 1, 'two' => 2]
// pull删除指定key的数据,并返回它 $collection = collect(['product_id' => 'prod-100', 'name' => 'Desk']); $collection->pull('name');// 'Desk' $collection->all(); // ['product_id' => 'prod-100']
// push $collection = collect([1, 2, 3, 4]); $collection->push(5); $collection->all(); // [1, 2, 3, 4, 5]
// put增加一个键值对应 $collection = collect(['product_id' => 1, 'name' => 'Desk']); $collection->put('price', 100); $collection->all(); // ['product_id' => 1, 'name' => 'Desk', 'price' => 100]
// random返回随机元素 $collection = collect([1, 2, 3, 4, 5]); $collection->random(); $random = $collection->random(3); // 取出3个随机元素 $random->all();
// reduce将数组压缩为一个值,将上一次的计算结果作为$carry引入 $collection = collect([1, 2, 3]); $total = $collection->reduce(function ($carry, $item) { ? ? return $carry + $item; }); // 6 $collection->reduce(function ($carry, $item) { ? ? return $carry + $item; }, 4);// 提供第一轮遍历时$carry的默认值,否则为null // 10
// 如果是关联数组 $collection = collect([ ? ? 'usd' => 1400, ? ? 'gbp' => 1200, ? ? 'eur' => 1000, ]); $ratio = [ ? ? 'usd' => 1, ? ? 'gbp' => 1.37, ? ? 'eur' => 1.22, ]; $collection->reduce(function ($carry, $value, $key) use ($ratio) { ? ? return $carry + ($value * $ratio[$key]); }); // 4264
// reject与filter相反,从数组中去除满足回调函数测试的元素 $collection = collect([1, 2, 3, 4]); $filtered = $collection->reject(function ($value, $key) { ? ? return $value > 2; }); $filtered->all(); // [1, 2]
// replace将原数组中的项修改为提供的匹配项,数字索引也会替换 $collection = collect(['Taylor', 'Abigail', 'James']); $replaced = $collection->replace([1 => 'Victoria', 3 => 'Finn']); $re = $replaced->all(); // ['Taylor', 'Victoria', 'James', 'Finn'] // 如果是merge,将返回['Taylor', 'Abigail', 'James', 'Victoria', 'Finn']
// replaceRecursive可以替换原元素中更深层的键值 $collection = collect([ ? ? 'Taylor', ? ? 'Abigail', ? ? [ ? ? ? ? 'James', ? ? ? ? 'Victoria', ? ? ? ? 'Finn' ? ? ] ]);
$replaced = $collection->replaceRecursive([ ? ? 'Charlie', ? ? 2 => [1 => 'King'] ]); $replaced->all(); // ['Charlie', 'Abigail', ['James', 'King', 'Finn']]
// reverse将原数组倒序排列,保留原索引 $collection = collect(['a', 'b', 'c', 'd', 'e']); $reversed = $collection->reverse(); $reversed->all(); /* ? ? [ ? ? ? ? 4 => 'e', ? ? ? ? 3 => 'd', ? ? ? ? 2 => 'c', ? ? ? ? 1 => 'b', ? ? ? ? 0 => 'a', ? ? ] */
// search搜索指定的元素,找到返回其第一次出现的索引,未找到则返回false $collection = collect([2, 4, 6, 8]); $collection->search(4); // 1 // 如果增加$strict=true的参数,则会进行严格匹配 collect([2, 4, 6, 8])->search('4', $strict = true); // false // 也可以用回调函数作为参数,则表示搜索第一次满足回调函数测试的元素 collect([2, 4, 6, 8])->search(function ($item, $key) { ? ? return $item > 5; }); // 2
// shift跟pop相对,删除并返回第一个元素 $collection = collect([1, 2, 3, 4, 5]); $collection->shift(); // 1 $collection->all(); // [2, 3, 4, 5]
// shuffle随机打乱所有元素,返回一个新collection $collection = collect([1, 2, 3, 4, 5]); $shuffled = $collection->shuffle(); $shuffled->all(); // [3, 2, 5, 1, 4] - (generated randomly)
// sliding每几个元素为一组,$step表示往前的步进数,默认为1 $collection = collect([1, 2, 3, 4, 5]); $chunks = $collection->sliding(3, $step= 2); $re = $chunks->toArray(); // [[1, 2, 3], [3, 4, 5]] $chunks = $collection->sliding(2); $chunks->toArray(); // [[1, 2], [2, 3], [3, 4], [4, 5]]
// skip跳过前面的几个元素,返回一个新collection $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $collection = $collection->skip(4); $collection->all(); // [5, 6, 7, 8, 9, 10]
// skipUntil跳过前面若干元素,直到碰到某一元素为止 $collection = collect([1, 2, 3, 4]); $subset = $collection->skipUntil(3); $subset->all(); // [3, 4] // 第二参数也可以是一个回调函数 $subset = $collection->skipUntil(function ($item) { ? ? return $item >= 3; }); $subset->all(); // [3, 4]
// skipWhile跟skipUntil的逻辑相反,符合条件时都skip,直到碰到不符合条件的为止 $collection = collect([1, 2, 3, 4]); $subset = $collection->skipWhile(function ($item) { ? ? return $item <= 3; }); $subset->all(); // [4]
// slice从某一索引处切分原数组 $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]
// sole测试数组中是否存在唯一的某一元素 collect([1, 2, 3, 4])->sole(function ($value, $key) { ? ? return $value === 2; }); // 2 // 也可以对关联数组进行测试 $collection = collect([ ? ? ['product' => 'Desk', 'price' => 200], ? ? ['product' => 'Chair', 'price' => 100], ]); $collection->sole('product', 'Chair'); // ['product' => 'Chair', 'price' => 100]
// sort得到排序后保留原key的数组 // sortDesc与sort用法类似,得到的结果是相反的 $collection = collect([5, 3, 1, 2, 4]); $sorted = $collection->sort(); $sorted->values()->all(); // [1, 2, 3, 4, 5]
// sortBy可让关联数组按某指定键进行排序 // sortByDesc与sortBy用法类似,得到的结果是相反的 $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], ? ? ] */
// sortBy可以接收第二个参数,指定排序的依据 // 详见https://www.php.net/manual/en/function.sort.php $collection = collect([ ? ? ['title' => 'Item 1'], ? ? ['title' => 'Item 12'], ? ? ['title' => 'Item 3'], ]); $sorted = $collection->sortBy('title', SORT_NATURAL); $sorted->values()->all(); /* ? ? [ ? ? ? ? ['title' => 'Item 1'], ? ? ? ? ['title' => 'Item 3'], ? ? ? ? ['title' => 'Item 12'], ? ? ] */
// 还可以用回调函数自定义排序依据,如下面例子根据colors中元素个数排序 $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']], ? ? ] */
// sortKeys将数组按key进行排序, sortKeysDesc结果相反 $collection = collect([ ? ? 'id' => 22345, ? ? 'first' => 'John', ? ? 'last' => 'Doe', ]); $sorted = $collection->sortKeys(); $sorted->all(); /* ? ? [ ? ? ? ? 'first' => 'John', ? ? ? ? 'id' => 22345, ? ? ? ? 'last' => 'Doe', ? ? ] */
// splice返回从指定索引位置开始的一段数组,原数据将只剩下前部分 $collection = collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2); $chunk->all(); // [3, 4, 5] $collection->all(); // [1, 2]
// 如果splice有第二个参数,则会限制长度 $chunk = $collection->splice(2, 1); $chunk->all(); // [3] $collection->all(); // [1, 2, 4, 5]
// 如果splice有第三个参数,则会把第三个参数放回原数组被切除的位置 $chunk = $collection->splice(2, 1, [10, 11]); $chunk->all(); // [3] $collection->all(); // [1, 2, 10, 11, 4, 5]
// split将原数组切分成几个部分 $collection = collect([1, 2, 3, 4, 5]); $groups = $collection->split(3); $groups->all(); // [[1, 2], [3, 4], [5]]
// splitIn在把原数组切分成几部分时,尽量除最后一项前的元素填满 $collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $groups = $collection->splitIn(3); $groups->all(); // [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
// sum求数组元素之和 collect([1, 2, 3, 4, 5])->sum(); // 15
// sum可以指定某字段键进行求和 $collection = collect([ ? ? ['name' => 'JavaScript: The Good Parts', 'pages' => 176], ? ? ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096], ]);
$collection->sum('pages'); // 1272
// 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相当于limit,与skip相对 $collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(3); $chunk->all(); // [0, 1, 2]
// 如果参数为负数,则表示从末尾开始取 $collection = collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(-2); $chunk->all(); // [4, 5]
// takeUntil用法与skipUntil类似 // takeWhile用法与skipWhile类似
// tap可以在一个回调函数闭包中处理collection副本而不影响原数据,不中断链式操作 collect([2, 4, 3, 1, 5]) ? ? ->sort() ? ? ->tap(function ($collection) { ? ? ? ? Log::debug('Values after sorting', $collection->values()->all()); ? ? }) ? ? ->shift(); // 1
// times以第一个数字为次数,返回一个经回调函数处理的数组 $collection = Collection::times(10, function ($number) { ? ? return $number * 9; }); $collection->all(); // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
// toArray转为数组 $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* ? ? [ ? ? ? ? ['name' => 'Desk', 'price' => 200], ? ? ] */
// toJson转为JSON字符串 $collection = collect(['name' => 'Desk', 'price' => 200]); $collection->toJson(); // '{"name":"Desk", "price":200}'
// transform跟map类似,但是会直接改变原collection $collection = collect([1, 2, 3, 4, 5]); $collection->transform(function ($item, $key) { ? ? return $item * 2; }); $collection->all(); // [2, 4, 6, 8, 10]
// union计算并集,如果一个键在原数组中已经存在,则保留原键值 $collection = collect([1 => ['a'], 2 => ['b']]); $union = $collection->union([3 => ['c'], 1 => ['d']]); $union->all(); // [1 => ['a'], 2 => ['b'], 3 => ['c']]
// unique返回所有独一无二不重复的元素,返回带key的结果;有重复值时取第一个,普通数组、关联数组类似 // uniqueStrict是unique的严格版本 $collection = collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4]
// unless与when相对,表示条件不成立时才执行回调函数 $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]
// unlessEmpty相当于whenNotEmpty // unlessNotEmpty相当于whenEmpty
// unwrap得到collection中的数组 Collection::unwrap(collect('John Doe')); // ['John Doe']
Collection::unwrap(['John Doe']); // ['John Doe']
Collection::unwrap('John Doe'); // 'John Doe'
// values返回一个新的collection,key将重置为连续整数,去掉原有关联数组的key $collection = collect([ ?? ?'key1'=>10, ? ? 10 => ['product' => 'Desk', 'price' => 200], ? ? 11 => ['product' => 'Desk', 'price' => 200], ]);
$values = $collection->values(); $re = $values->all(); /* ? ? [ ? ? ? ? 0 => 10, ? ? ? ? 1 => ['product' => 'Desk', 'price' => 200], ? ? ? ? 2 => ['product' => 'Desk', 'price' => 200], ? ? ] */
// when跟unless相对,表示条件满足时执行回调函数 $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]
// whenEmpty用法与when类似,当collection为空时执行 // whenNotEmpty用法与when类似,当collection为非空时执行
// where过滤出符合条件的元素 // whereStrict是where的严格版本 $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], ? ? ] */
// whereBetween过滤出符合在一定区间条件的元素 // whereNotBetween是相反的语句 $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], ? ? ] */
// whereIn过滤中某一键值在指定数组中的元素 // whereInStrict是whereIn的严格版本 // whereNotIn // whereNotInStrict $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' => 'Desk', 'price' => 200], ? ? ? ? ['product' => 'Bookcase', 'price' => 150], ? ? ] */
// whereInstanceOf过滤是某一类实例的元素 use App\Models\User; use App\Models\Post;
$collection = collect([ ? ? new User, ? ? new User, ? ? new Post, ]); $filtered = $collection->whereInstanceOf(User::class); $filtered->all(); // [App\Models\User, App\Models\User]
// whereNull返回相应键值为null的项 // whereNotNull与之相反 $collection = collect([ ? ? ['name' => 'Desk'], ? ? ['name' => null], ? ? ['name' => 'Bookcase'], ]); $filtered = $collection->whereNull('name'); $filtered->all(); /* ? ? [ ? ? ? ? ['name' => null], ? ? ] */
// wrap将参数中的内容打包成数组 use Illuminate\Support\Collection;
$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将两个数组的元素对应构成新的数组 $collection = collect(['Chair', 'Desk']); $zipped = $collection->zip([100, 200]); $zipped->all(); // [['Chair', 100], ['Desk', 200]]
?
|