如何格式化以下laravel集合

时间:2019-01-20 09:15:43

标签: laravel eloquent laravel-collection

提前谢谢!我在Laravel中有以下收藏。

$data = collect([
    [
        'id' => 1,
        'filter' => 'brand',
        'value' => 'apple'
    ],
    [
        'id' => 2,
        'filter' => 'color',
        'value' => 'red'
    ],
    [
        'id' => 3,
        'filter' => 'color',
        'value' => 'blue'
    ],
    [
        'id' => 3,
        'filter' => 'storage',
        'value' => '8GB'
    ]
]);

我完全需要这样:


[
    "brand" => ["apple"],
    "color" => ["red", "blue"],
    "storage" => ["8GB"]
]

如何像上面这样格式化?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。

$grouped = $collection->mapToGroups(function ($item, $key) {
    return [$item['filter'] => $item['value']];
});

$grouped->toArray();

https://laracasts.com/discuss/channels/eloquent/need-help-with-formatting-laravel-collection#reply=486863