How to remove duplicates in collection?

孤街浪徒 提交于 2020-06-24 21:34:11

问题


I have collection in 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;
    }

回答1:


$unique = $collection->unique();



回答2:


$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



来源:https://stackoverflow.com/questions/44169551/how-to-remove-duplicates-in-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!