laravel collection 重组为嵌套

laravel collection restructure to nested

我将查询结果包装到 larave collection:

[
    [
        'group_id' => 1,
        'value_id' => 1
    ],
    [
        'group_id' => 1,
        'value_id' => 2
    ],
    [
        'group_id' => 2,
        'value_id' => 3
    ]
];

这个collection。 我该怎么做

[
    [
        'group_id' => 1,
        'values' => [
            [
                'value_id' => 1
            ],
            [
                'value_id' => 2
            ]
        ]
    ],
    [
        'group_id' => 2,
        'values' => [
            [
                'value_id' => 3
            ]
        ]
    ]
];

最好用laravel collection methods.I 会非常感谢你

使用groupBymapforget...有很多方法可以做,只需阅读文档即可。

$data = [
    [
        'group_id' => 1,
        'value_id' => 1
    ],
    [
        'group_id' => 1,
        'value_id' => 2
    ],
    [
        'group_id' => 2,
        'value_id' => 3
    ]
];

$data = collect($data)
    ->groupBy('group_id')
    ->map(function($item, $key){
        return [
            'group_id' => $key,
            'values' => collect($item)->map(function($item){
                return collect($item)->forget('group_id')->all();
            })->toArray()
        ];
    })
    ->toArray();

dd($data);

输出:

array:2 [
  1 => array:2 [
    "group_id" => 1
    "values" => array:2 [
      0 => array:1 [
        "value_id" => 1
      ]
      1 => array:1 [
        "value_id" => 2
      ]
    ]
  ]
  2 => array:2 [
    "group_id" => 2
    "values" => array:1 [
      0 => array:1 [
        "value_id" => 3
      ]
    ]
  ]
]