Skip to content
Advertisement

Grouped collection to associative array

I need to achive array in format showed at the end, I’m using laravel collections

$query->get()->groupBy(‘COLOR’)->toArray();

array:2 [
  "GREEN" => array:123 [
    0 => array:2 [
      "color" => "GREEN"
      "id" => "956"
    ]
    1 => array:2 [
      "color" => "GREEN"
      "id" => "50"
    ]
...

Format I need to achive:

array:1 [
  "GREEN" => array:123 [
    0 => "956"
    1 => "50"
...
]

Advertisement

Answer

You should be able to do all of this with the Collection class:

$query->get()->groupBy('COLOR')->map->pluck('id')->toArray()
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement