如何删除集合中的重复项?

时间:2017-05-24 22:35:51

标签: laravel laravel-5.3 laravel-5.4

我收集了Laravel:

let classB = class extends...

这是相同的项目。如何删除其中一个?

完整代码是:

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

3 个答案:

答案 0 :(得分:14)

$unique = $collection->unique();

答案 1 :(得分:4)

$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'],
]);

那么假设您希望该品牌具有独特性,在这种情况下,您应该只获得两个品牌“ Apple”和“ Samsung”

$unique = $collection->unique('brand');

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

这取自https://laravel.com/docs/master/collections#method-unique

答案 2 :(得分:0)

您可以使用 groupBy + Max 从 SQL 级别唯一化数据集 下面试试

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');