How to remove duplicates in collection?

前端 未结 3 1678
逝去的感伤
逝去的感伤 2021-02-12 11:56

I have collection in Laravel:

Collection {#450 ▼
  #items: array:2 [▼
    0 => Announcement {#533 ▶}
    1 => Announcement {#553 ▶}
  ]
}

相关标签:
3条回答
  • 2021-02-12 12:07
    $unique = $collection->unique();
    
    0 讨论(0)
  • 2021-02-12 12:24
    $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'],
    ]);
    

    Then let's say you want the brand to be unique, in this case you should only get two brands 'Apple', and 'Samsung'

    $unique = $collection->unique('brand');
    
    $unique->values()->all();
    /*
        [
            ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
            ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
        ]
    */
    

    This is taken from https://laravel.com/docs/master/collections#method-unique

    0 讨论(0)
  • 2021-02-12 12:26

    You can unique the data set from the SQL level with groupBy + Max Try below

    YourModelName::select(DB::raw('max(`town_short_name`) as town' 'town_long_name'))
            ->groupBy(['town_short_name'])
            ->without('postalCode','country','countryState')
            ->where('town_short_name','like','%'.$townName.'%')
            ->limit(100)
            ->orderBy('town_short_name');
    
    0 讨论(0)
提交回复
热议问题