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"
    ]
    ....
7
  • a suggestion: $companies = Company::select(['id','name'])->get()->toArray()->map(function($item){ return array_flatten($item); }); Commented Aug 5, 2017 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? Commented Aug 5, 2017 at 23:16
  • sure, sorry, you can use array_map instead, or put toArray() after map(). Commented Aug 5, 2017 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(); Commented Aug 5, 2017 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) Commented Aug 5, 2017 at 23:36

1 Answer 1

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",
   ]
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.