【问题标题】:Laravel collection group by like category nameLaravel 集合组按类似类别名称
【发布时间】:2020-02-22 00:24:45
【问题描述】:

假设我有一个对象的集合,每个水果都有一个共享的颜色名称。

我想把水果按颜色名称分组

Red
Red
Red
Green
Green
Red
Green

Becomes

Red
 Apple
 Strawberry 
 Cherry
 Cranberry

Green
  Grape
  Watermelon
  Pear

  $all_fruits->map(function ($item, $key) {

        });

非常感谢所有帮助。

【问题讨论】:

标签: laravel laravel-5


【解决方案1】:

你可能只是你groupBy函数:

$allFruits->groupBy(function ($item) {
    // Or $item->color_name;
    return $item['color_name'];
});

【讨论】:

    【解决方案2】:
    $collected = $fruits->mapToGroups(function ($item, $key) {
                    return
                        [$item->fruitColor => $item->toArray()];
            });
    

    【讨论】:

    • 添加口头解释通常有助于回答
    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2013-10-06
    • 2021-07-25
    • 2017-05-06
    相关资源
    最近更新 更多