40

I have a large SQL statement that I am executing like so:

$result = DB::select($sql);

For example

$result = DB::select('select * from users');

I'd like the result to be an array - but at the moment it returns a structure like so, an array with Objects...

Array
(
    0 => stdClass::__set_state(array(
        'id' => 1,
        'first_name' => 'Pavel',
        'created_at' => '2015-02-23 05:46:33',
    )),
    1 => stdClass::__set_state(array(
        'id' => 2,
        'first_name' => 'Eugene',
        'created_at' => '2016-02-23 05:46:34',
    )),
...etc...

)

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191

13 Answers13

54

Seems like you need to cast the stdClass Objects as Array so you can have the structure you are looking for

$result = array_map(function ($value) {
    return (array)$value;
}, $result);
Jose Mujica
  • 678
  • 1
  • 6
  • 9
34

The best solutions looking at performance would be changing method how data is grabbed from database:

// get original model
$fetchMode = DB::getFetchMode();
// set mode to custom
DB::setFetchMode(\PDO::FETCH_ASSOC);
// get data
$result = DB::select($sql);
// restore mode the original
DB::setFetchMode($fetchMode);

Obviously if you want to get all the data as array, it will be enough to change in config/database.php from:

'fetch'       => PDO::FETCH_CLASS,

into

'fetch'       => PDO::FETCH_ASSOC,

and then running only:

$result = DB::select($sql);

will return you multidimensional array instead of array of objects

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
13

Here is another approach that is worth to be mentioned:

$resultArray = json_decode(json_encode($result), true);
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
11

toArray() method converts collection to an array. Models are converted to arrays too:

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

So, I guess you're doing something wrong. If you want more help, please update you question with all related code.

Also, only Eloquent collections (models) have toArray() method.

To use this method, use Eloquent:

$result = \App\User::all()->toArray();
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
4

For laravel/lumen 5.4 (that uses illuminate/database 5.4):

$pdo = DB::getPdo();
$statement = $pdo->prepare($yourQuery);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
$statement->execute();
$results = $statement->fetchAll();

Or listen to Illuminate\Database\Events\StatementPrepared event: Laravel 5.4 - How to set PDO Fetch Mode?

Tobias Sette
  • 185
  • 12
3

you can try this

DB::table('commune')->where('Commune','<>', 'ND')->orderBy('Commune')->get()->pluck('Commune');
Mourad MAMASSI
  • 849
  • 1
  • 11
  • 14
1

You can make a collection in order to use toArray(), very simple approach:

$result = DB::table('users')->get();
$data = collect($result)->map(function($x){ return (array) $x; })->toArray(); 
Mahmoud Abdelsattar
  • 1,299
  • 1
  • 15
  • 31
  • The accepted answer uses the same concept of array_map-ing, but without extra conversion to and out from collection. I'm afraid you have not contributed much. – Yevgeniy Afanasyev Jan 12 '20 at 00:04
0

Try this

$result = DB::select($sql);
$arr = [];
foreach($result as $row)
{
    $arr[] = (array) $row;
}
huuuk
  • 4,597
  • 2
  • 20
  • 27
  • This is wrong. I got: local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function get() on array' – Yevgeniy Afanasyev May 30 '16 at 05:05
  • UPDATE exception 'ErrorException' with message 'call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\MySqlConnection' does not have a method 'selectRaw'' – Yevgeniy Afanasyev May 30 '16 at 05:09
  • @huuuk, select accepts not only column names: `$users = DB::select('select * from users where active = ?', [1]);` - Also, your examples doesn't work. To make last one get something, you need to remove `->get()` – Alexey Mezenin May 30 '16 at 05:14
  • @AlexMezenin I'm sorry, I was wrong. You are right. I'm a bit confused wit `Eloquent` – huuuk May 30 '16 at 05:16
0

You can do this way..

At the top

use DB;
use PDO;

--------------------

DB::setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode as array

$result = DB::select('select * from users');

For example, now you can get result like this way.

$first_email = $result[0]['email'];

Now you can change to default fetch mode.

DB::setFetchMode(PDO::FETCH_CLASS);
Parvez Rahaman
  • 4,269
  • 3
  • 22
  • 39
0

Good to pick through the answers here to understand the reasons. Here's my version that I settled on:

$users = collect($users) // turn the top level array into a collection
    ->map(fn($user) => (array) $user) // cast each object to an array
    ->toArray(); // convert top level collection back to an array

You had an array of objects. Now you will have an array of arrays. Note that this doesn't do a recursive conversion of the internal array, but since it's only one level deep you're fine.

GuruBob
  • 855
  • 1
  • 10
  • 21
-1

One tricky and simple way :

//Got array in stdClass converting to JSON
$temp1= json_encode($result);


//JSON to Array
$temp2= json_decode($temp1,1);`

May be it will help you

Atika
  • 1,025
  • 2
  • 6
  • 17
Vishal
  • 129
  • 1
  • 1
  • 10
-2

You can use this one. It's worked for me.

$query = DB::table('user')->select(['id','name'])->get();
$userlist = $query->toArray();
Chandan Sharma
  • 2,321
  • 22
  • 22
-4

Easiest way is using laravel toArray function:

public function toArray()
{
    return array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $this->items);
}
Mohsen
  • 4,049
  • 1
  • 31
  • 31
  • toArray() is method, not just function. And it converts collection to an array. I don't have a collection for starters, I have an array of objects. Only because DB::select($sql); returns array of objects. So your answer is not help. – Yevgeniy Afanasyev Feb 08 '18 at 22:19