根据重复计数区分和排序集合
Distinct and sort collection based on duplicate count
我有以下合集
$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
方法删除重复项,但找不到要对它们进行排序的方法。
你可以用 mapWithKeys()
https://laravel.com/docs/8.x/collections#method-mapwithkeys
$collection = $collection->groupBy('id')->mapWithKeys(function (Collection $row) {
return [$row->count() => $row->first()];
})->sortKeysDesc();
我有以下合集
$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
方法删除重复项,但找不到要对它们进行排序的方法。
你可以用 mapWithKeys()
https://laravel.com/docs/8.x/collections#method-mapwithkeys
$collection = $collection->groupBy('id')->mapWithKeys(function (Collection $row) {
return [$row->count() => $row->first()];
})->sortKeysDesc();