【问题标题】:Group Laravel Collection By Children儿童组 Laravel 合集
【发布时间】:2020-10-27 17:37:03
【问题描述】:

我想知道是否可以使用 laravel 集合来对具有相同子项的项目进行分组。如果您看下面的示例,我想将 id 为 1 和 4 以及 2 和 3 的订单组合在一起。 id 为 5 的订单将在其自己的组中。这有意义吗?

$orders = collect([
    [
        'id' => 1,
        'items' => [
            ['id' => 1, 'name' => 'Product A'],
            ['id' => 2, 'name' => 'Product B']
        ]
    ],
    [
        'id' => 2,
        'items' => [
            ['id' => 3, 'name' => 'Product C'],
            ['id' => 4, 'name' => 'Product D']
        ]
    ],
    [
        'id' => 3,
        'items' => [
            ['id' => 3, 'name' => 'Product C'],
            ['id' => 4, 'name' => 'Product D']
        ]
    ],
    [
        'id' => 4,
        'items' => [
            ['id' => 1, 'name' => 'Product A'],
            ['id' => 2, 'name' => 'Product B']
        ]
    ],
    [
        'id' => 5,
        'items' => [
            ['id' => 1, 'name' => 'Product A'],
            ['id' => 2, 'name' => 'Product B'],
            ['id' => 3, 'name' => 'Product C']
        ]
    ]
]);

【问题讨论】:

  • 所以项目会出现在多个组中?
  • 您能指定一个类别吗?在数据透视表中
  • @Jerodev:没错。我已经发布了一个答案,应该可以满足我的需要。在寻求帮助之前应该多摆弄一下

标签: php arrays laravel collections


【解决方案1】:

好的,我想通了——这应该可以工作,尽管我需要确保每个 items 数组都按 id 排序。

        $orders->groupBy(function ($order) {
            return implode('', array_column($order['items'], 'id'));
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2019-05-07
    • 1970-01-01
    相关资源
    最近更新 更多