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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44169551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:02:25  来源:igfitidea点击:

How to remove duplicates in collection?

laravellaravel-5.3laravel-5.4

提问by Blablacar

I have collection in Laravel:

我在 Laravel 中有收藏:

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

It is the same items. How ti delete one of them?

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

Full code is:

完整代码为:

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;
    }

回答by Mevlüt?zdemir

$unique = $collection->unique();

回答by Richard

$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'

然后假设您希望品牌独一无二,在这种情况下,您应该只获得“Apple”和“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

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