犹豫工作中,看到同事写的代码,太优美了。所以忍不住赏析一番,记录下来以免以后忘记。
数据整合
获取uid%16后组装的数据
$uid_group = $uids->mapToGroups(function ($item) {
$num = str_pad((string)($item % 16), 2, '0', STR_PAD_LEFT);
return [$num => $item];
});
- mapToGroups()
mapToGroups 方法通过给定的回调函数对集合项进行分组。该回调函数应该返回一个包含单个键 / 值对的关联数组,从而生成一个分组值的新集合:
$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'],
]
*/
$grouped->get('Sales')->all();
// ['John Doe', 'Jane Doe']
————————————————
原文作者:Laravel China 社区文档:《Laravel 8 中文文档(8.5)》
转自链接:https://learnku.com/docs/laravel/8.5/collections/10384#method-maptogroups
版权声明:翻译文档著作权归译者和 LearnKu 社区所有。转载请保留原文链接
- str_pad()
- str_pad() 函数把字符串填充为新的长度
- str_pad(string,length,pad_string,pad_type)
参数 | 描述 |
---|---|
string | 必需。规定要填充的字符串。 |
length | 必需。规定新字符串的长度。如果该值小于原始字符串的长度,则不进行任何操作。 |
pad_string | 可选。规定供填充使用的字符串。默认是空白。 |
pad_type | 可选。规定填充字符串的哪边。 可能的值:
|
数组操作(larvel)
$uid_coin = collect($parallel->wait())
->filter()
->collapse()
->pluck('gold', 'uid')
->toArray();
-
collect() {#collection-method}
collect 方法返回一个新的 Collection 实例,其中包含当前集合中的项 -
collapse() {#collection-collapse}
collapse 方法将数组集合合并为单一的集合
$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]
- pluck() {#collection-method}
和array_column()类似
pluck 可以获取集合中指定键对应的所有值:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
协程操作
$parallel = new Parallel(10);
foreach ($uid_group as $num => $item) {
$parallel->add(function () use ($num, $item, $builder) {
return (clone $builder)->setTable($builder->getTable() . $num)
->whereIn('uid', $item)
->get(['uid', 'gold','silver']);
});
}
//去空,整合成二维,再提取成[uid=>gold]
$uid_coin = collect($parallel->wait())
->filter()->collapse()->pluck('gold', 'uid')->toArray();
这个没啥好讲, 中规中矩文档操作