如何删除 collection 中的重复项?

How to remove duplicates in collection?

我有 collection Laravel:

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

是同款商品。如何删除其中一个?

完整代码为:

public function announcements()
    {

        $announcements = $this->categories_ann->map(function ($c) {
            return $c->announcements->map(function ($a) {
                $a->subsribed = true;

                return $a;
            });
        });

        $flattened = $announcements->groupBy("id")->flatten();

        return $flattened;
    }
$unique = $collection->unique();
$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

您可以使用 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');