Home > Software design >  laravel collection restructure to nested
laravel collection restructure to nested

Time:02-09

I have query result wrapped to larave collection:

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

this collection. How can i make this

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

Preferably with laravel collection methods.I will be very grateful to you.

CodePudding user response:

Use groupBy, map, forget... There are many ways that you can do, just by reading the documentation.

$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);

Output :

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
      ]
    ]
  ]
]
  •  Tags:  
  • Related