惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
博客园 - 聂微东
V
Visual Studio Blog
博客园_首页
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
F
Fortinet All Blogs
C
Check Point Blog
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - php、凯

优豆云:免费云服务的宝藏之选 docker xtom无法访问的解决办法 ubuntu 卸载php laravel response返回值精度问题 debian 系统搭建rsync+sersync实现实时同步 docker 搭建debian+nginx+php(含composer的扩展)+mysql+mongo+redis lnmp卸载删除多余的php版本 laravel操作mongo详细说明 Laradock中文文档 docker-composer 简单教程 laravel jwt实践 Laravel实现from的curl文件转发 docker添加mongo4.0.3并配置复制集 docker创建mysql5.7.22并配置主从 docker相关内容 Windows7安装 docker-compose的过程 史上最简单的Docker入门教程 MySQL触发器使用详解 存储过程
laravel collet分组
php、凯 · 2020-12-15 · via 博客园 - php、凯

转自 : https://my.oschina.net/ives/blog/825988

collect提供了大量对数组的处理方法,使处理数组更加方便,以下函数在项目中可以考虑借鉴

一、sum() 用于求和

sum()    
示例1.:collect([1,2,3])->sum();

二、unique()

unique方法返回集合中所有的唯一数据项:

$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
返回的集合保持原来的数组键,在本例中我们使用values方法重置这些键为连续的数字索引。

处理嵌套数组或对象时,可以指定用于判断唯一的键:

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


你还可以指定自己的回调用于判断数据项唯一性:

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