cameraguy258
cameraguy258

Reputation: 689

groupBy as indexed array in Laravel

Suppose I have a collection like this:

$collection = [
  App\User {name: 'Bob', age: 20},
  App\User {name: 'Joe', age: 22},
  App\User {name: 'Lisa', age: 20}
]

and I group them like $collection->groupBy('age'). I get this result:

[
  "20" => [
    App\User {name: 'Bob', age: 20},
    App\User {name: 'Lisa', age: 20},
  ],
  "21" => [
    App\User {name: 'Joe', age: 22}
  ]
]

I'd like to remove the associative keys and just use an indexed array, like this:

[
  [
    App\User {name: 'Bob', age: 20},
    App\User {name: 'Lisa', age: 20},
  ],
  [
    App\User {name: 'Joe', age: 22]
  ]
]

Is this possible to do with a Laravel collection method? Thanks in advance for any pointers!

Upvotes: 1

Views: 563

Answers (2)

nekooee
nekooee

Reputation: 325

also you can use ->unique() instead groupBy. In this helper, it is indexed from zero.

Upvotes: 0

namelivia
namelivia

Reputation: 2735

Use array_values: https://www.php.net/manual/en/function.array-values.php

array_values($collection->groupBy('age'));

More Laravel way would be

$collection->groupBy('age')->values();

Upvotes: 3

Related Questions