'I am trying to group values of collection by keys
This is far more simple to explain by providing example. I got collection like this.
[
[
'brand' => 'brand1',
'model' => 'model1'
],[
'brand' => 'brand2',
'model' => 'model2'
],[
'brand' => 'brand3',
'model' => 'model3'
],[
'brand' => 'brand4',
'model' => 'model4'
],
]
But I would like to have manipulate it so I have collection like looking this.
[
'brand' => ['brand1', 'brand2', 'brand3', 'brand4' ],
'model' => ['model1', 'model2', 'model3', 'model4' ]
]
So the question is what I need to do to transform the first format into the other one. Preferably without the using of loops (I know how to do it this way) and with use of laravel collection methods as a one liner.
EDIT. I forgot to mention that the brand and model is just example and I need more general solution that would work if collection contains N number of keys that are somewhat unknown/random.
Solution 1:[1]
Use "pluck" function.
To exactly recreate the example you wrote:
$collection = Collection::select('brand', 'model')->get();
$array = [
'brand' => $collection->pluck('brand')->toArray(),
'model' => $collection->pluck('model')->toArray()
];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luca P. |
