0

How can I fetch an array of numeric arrays in Laravel?


Here's what I've got:

 $companies = Company::select(['id','name'])->get()->toArray();

This gives me back:

array:21 [
    0 => array:2 [
      "id" => 21
      "name" => "Cool Company"
    ]
    1 => array:2 [
      "id" => 4
      "name" => "Bacon Co"
    ]
    ....

But I want:

array:21 [
    0 => array:2 [
      21,
      "Cool Company"
    ]
    1 => array:2 [
      4,
      "Bacon Co"
    ]
    ....
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • a suggestion: $companies = Company::select(['id','name'])->get()->toArray()->map(function($item){ return array_flatten($item); }); – Naco Aug 05 '17 at 23:14
  • 1
    @user3681740 Don't think you can `->map` after it's an array, and I think I'd want `array_values` instead, but regardless, surely I shouldn't have to do that? – mpen Aug 05 '17 at 23:16
  • sure, sorry, you can use array_map instead, or put toArray() after map(). – Naco Aug 05 '17 at 23:19
  • I'd like to know if this works for you: Company::select(['id','name'])->get()->map(function($item){ return array_flatten($item->toArray()); })->toArray(); – Naco Aug 05 '17 at 23:30
  • @user3681740 Yeah, it does give the correct result, it's just a stupid number of function calls and iterations for something so simple -- something that PDO could have easily given me with `->fetchAll(PDO::FETCH_NUM)` – mpen Aug 05 '17 at 23:36
  • Possible duplicate of [Laravel - get DB result without table column name](https://stackoverflow.com/questions/42978115/laravel-get-db-result-without-table-column-name) – user3743266 Aug 05 '17 at 23:37
  • @user3743266 Pretty sure they randomly changed what `pluck` does between 4.2 and 5.2, so that solution is no longer applicable. [details here](https://stackoverflow.com/questions/34405138/laravel-5-2-pluck-method-returns-array#comment60756426_34405138) – mpen Aug 06 '17 at 02:19

1 Answers1

1

If you need this exact output you can do

$companies = App\Company::pluck('name', 'id')
    ->map(function ($name, $id) { 
        return [$id, $name]; 
    })
    ->values()
    ->toArray();

Output:

=> [
     [
       4,
       "Bacon Co",
     ],
     [
       21,
       "Cool Company",
     ],
   ]

Not sure what you're doing with it afterwards but maybe just the output of pluck() will suffice

$companies = App\Company::pluck('name', 'id')->toArray();
=> [
     4 => "Bacon Co",
     21 => "Cool Company",
   ]
peterm
  • 91,357
  • 15
  • 148
  • 157
  • No, I don't want it to be indexed. I'm serializing to JSON and I need an array, not an object. Your first solution will work I guess. Thanks – mpen Aug 06 '17 at 02:21