zoukankan      html  css  js  c++  java
  • laravel collet分组

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

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

    一、sum() 用于求和

    sum()    
    示例1.:collect([1,2,3])->sum();//6
    示例2.:$list = [
                ['name'=>'支付宝','money'=>'10'],
                ['name'=>'微信','money'=>'10.3'],
            ];
            collect($list)->sum('money');//20.3
    

    二、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'],
        ]
    */
  • 相关阅读:
    go语言浅析二叉树
    Go语言冒泡、选择、插入、快速排序实战浅析
    go语言教程之浅谈数组和切片的异同
    实测Maven上传jar包到私服的方法归纳
    干货|Dubbo社区开发者日经验分享
    Go语言系列开发之延迟调用和作用域
    mysql中间件分享(Mysql-prxoy,Atlas,DBProxy,Amoeba,cobar,TDDL)
    时间操作
    大型网站架构设计方向初探
    C#输入法
  • 原文地址:https://www.cnblogs.com/phpk/p/14139963.html
Copyright © 2011-2022 走看看