【问题标题】:Distinct and sort collection based on duplicate count根据重复计数对集合进行区分和排序
【发布时间】:2022-01-11 18:56:32
【问题描述】:

我有以下收藏

$collection = collect([
    ['id' => 1, 'name' => 'Design'],
    ['id' => 2, 'name' => 'Art'],
    ['id' => 3, 'name' => 'Comms'],
    ['id' => 2, 'name' => 'Art'],
    ['id' => 3, 'name' => 'Comms'],
    ['id' => 3, 'name' => 'Comms'],
]);

我只想要集合中唯一的项目,并且集合应该按重复的数量排序。因此,重复次数最多的项目必须出现在顶部,如下所示

$collection = collect([
        ['id' => 3, 'name' => 'Comms'],
        ['id' => 2, 'name' => 'Art'],
        ['id' => 1, 'name' => 'Design'],
    ]);

我可以使用unique 方法删除重复项,但找不到想要排序的对象。

【问题讨论】:

  • 或许您应该先对它们进行分组,以便获得计数,然后再映射它们以获得最终结果?
  • 您是如何获得该收藏的。这是需要更改的查询。
  • 您可以在集合中使用sortBy方法对数据进行排序。

标签: laravel laravel-collection


【解决方案1】:

你可以用mapWithKeys()做到这一点

https://laravel.com/docs/8.x/collections#method-mapwithkeys

$collection = $collection->groupBy('id')->mapWithKeys(function (Collection $row) {
    return [$row->count() => $row->first()];
})->sortKeysDesc();

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2015-09-18
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多