如何对 Laravel 的集合与数组类型的嵌套字段进行分组?

How to groupBy the collection of Laravel with the nested field of type array?

我有这个集合,我想更改此数据,以便键是分支 ID,值是项目:

{
    "data": [
        {
            "id": 5020,
            "category_id": 577,
            "branches": [
             {
               "id": 7,
               "title": "water",
             },
             {
               "id": 6,
               "title": "vegetable",
             }, 
        },
        {
            "id": 5025,
            "category_id": 577,
            "branches": [
             {
               "id": 7,
               "title": "water",
             },
        }
     ]
}

我想按分支 -> id 按此数据分组,如下所示:

{
    "data": [
        "7" : [
               {
                 "id": 5020,
                 "category_id": 577,
                 "branches": [
                    {
                       "id": 7,
                       "title": "water",
                    },
                    {
                       "id": 6,
                       "title": "vegetable",
                    }, 
               },
              {
                "id": 5025,
                "category_id": 577,
                "branches": [
                  {
                    "id": 7,
                    "title": "water",
                  },
                ] 
             }
           ],
        "6" : [
               {
                 "id": 5020,
                 "category_id": 577,
                 "branches": [
                    {
                       "id": 7,
                       "title": "water",
                    },
                    {
                       "id": 6,
                       "title": "vegetable",
                    }, 
               },

           ],
}

如何使用Laravel中的group By集合方法?我想要这样的数据,我的数据是集合类型

您可以在 groupBy 方法中使用回调来提供自定义逻辑。

示例:

collect($data)->groupBy(fn($item, $key) => $item['branches'][0]['id']);

但是在这个例子中我想建议你使用循环:

$myGroups = [];
foreach($data as $item) {
  foreach($item['branches'] as $branch) {
    $myGroups[$branch['id']][] = $item;
  }
}