32

Laravel output:

Array
(
    [0] = stdClass Object
    (
        [ID] = 5

    )

    [1] = stdClass Object
    (
        [ID] = 4

    )

)

I want to convert this into normal array. Just want to remove that stdClass Object. I also tried using ->toArray(); but I get an error:

Call to a member function toArray() on a non-object.

How can I fix this?

Functionalities have been Implemented on http://www.srihost.com

The Alpha
  • 143,660
  • 29
  • 287
  • 307
Your Friend
  • 1,119
  • 3
  • 12
  • 27
  • did this object came from the DB? i haven't used laravel, but maybe the have an API that results an associative array instead of objects. no need to convert the whole object and then transfer them into another array – Kevin Oct 03 '14 at 06:35
  • yes it came from DB.. – Your Friend Oct 03 '14 at 06:37
  • Duplicate question? http://stackoverflow.com/questions/28658891/converting-object-to-array-in-laravel/35414167#35414167 – Stefano Groenland Feb 15 '16 at 16:25

14 Answers14

45
foreach($yourArrayName as $object)
{
    $arrays[] = $object->toArray();
}
// Dump array with object-arrays
dd($arrays);

Or when toArray() fails because it's a stdClass

foreach($yourArrayName as $object)
{
    $arrays[] =  (array) $object;
}
// Dump array with object-arrays
dd($arrays);

Not working? Maybe you can find your answer here:

Convert PHP object to associative array

Community
  • 1
  • 1
Maurice
  • 1,342
  • 11
  • 21
39

UPDATE since version 5.4 of Laravel it is no longer possible.

You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:

DB::setFetchMode(PDO::FETCH_ASSOC);

// then
DB::table(..)->get(); // array of arrays instead of objects

// of course to revert the fetch mode you need to set it again
DB::setFetchMode(PDO::FETCH_CLASS);

For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});
Benyamin Limanto
  • 775
  • 10
  • 24
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
19

Just in case somebody still lands here looking for an answer. It can be done using plain PHP. An easier way is to reverse-json the object.

function objectToArray(&$object)
{
    return @json_decode(json_encode($object), true);
}
Selay
  • 6,024
  • 2
  • 27
  • 23
12

this worked for me:

$data=DB::table('table_name')->select(.......)->get();
$data=array_map(function($item){
    return (array) $item;
},$data);

or

$data=array_map(function($item){
    return (array) $item;
},DB::table('table_name')->select(.......)->get());
Adrian Enriquez
  • 8,175
  • 7
  • 45
  • 64
Touhid
  • 303
  • 3
  • 8
8

You can also get all the result always as array by changing

// application/config/database.php

'fetch' => PDO::FETCH_CLASS,
 // to
'fetch' => PDO::FETCH_ASSOC,

Hope this will help.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
6

this worked for me in laravel 5.4

$partnerProfileIds = DB::table('partner_profile_extras')->get()->pluck('partner_profile_id');
$partnerProfileIdsArray = $partnerProfileIds->all();

output

array:4 [▼
  0 => "8219c678-2d3e-11e8-a4a3-648099380678"
  1 => "28459dcb-2d3f-11e8-a4a3-648099380678"
  2 => "d5190f8e-2c31-11e8-8802-648099380678"
  3 => "6d2845b6-2d3e-11e8-a4a3-648099380678"
]

https://laravel.com/docs/5.4/collections#method-all

Coxxs
  • 460
  • 4
  • 9
scandar
  • 81
  • 1
  • 5
6

Use the toArray() method to convert an object to array:

$foo = Bar::first(); // Get object
$foo = $foo->toArray(); // Convert object to array
LobsterBaz
  • 1,752
  • 11
  • 20
Pablo Ramires
  • 357
  • 3
  • 4
5

It's also possible to typecast an object to an array. That worked for me here.

(array) $object;

will convert

stdClass Object
(
    [id] => 4
)

to

Array(
    [id] => 4
)

Had the same problem when trying to pass data from query builder to a view. Since data comes as object. So you can do:

$view = view('template', (array) $object);

And in your view you use variables like

{{ $id }}
NinoMarconi
  • 111
  • 1
  • 6
2

You need to iterate over the array

for ($i = 0, $c = count($array); $i < $c; ++$i) {
    $array[$i] = (array) $array[$i];
}

ans use (array) conversion because you have array of objects of Std class and not object itself

Example:

$users = DB::table('users')->get();

var_dump($users);

echo "<br /><br />";

for ($i = 0, $c = count($users); $i < $c; ++$i) {
    $users[$i] = (array) $users[$i];
}
var_dump($users);
exit;

Output for this is:

array(1) { [0]=> object(stdClass)#258 (8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }

array(1) { [0]=> array(8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } } 

as expected. Object of stdClass has been converted to array.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • i tried both methods.. same error `Call to a member function toArray() on a non-object ` – Your Friend Oct 03 '14 at 06:41
  • @user3436481 Have you tried using only `(array)` as I showed in my answer? You should edit your question and show how exactly you get data and how you use array conversion – Marcin Nabiałek Oct 03 '14 at 06:44
  • Iam getting data from laravel database ... it uses `std class` ...data is exactly same.... – Your Friend Oct 03 '14 at 06:46
  • If you're using Laravel properly, it uses model objects and collections, not StdClass objects – Mark Baker Oct 03 '14 at 07:19
  • 1
    @MarkBaker No, only Eloquent does it. If you use simple `Query\Builder` it returns exactly this `array` of `stdObjects` (by default, depending on the db config) – Jarek Tkaczyk Oct 03 '14 at 07:24
2

Object to array

$array = (array) $players_Obj;  

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump( (array) $object );

Output:

array(2) {
    'foo' => int(1)
    'bar' => int(2)
}
executable
  • 3,365
  • 6
  • 24
  • 52
Aslam Khan
  • 382
  • 2
  • 2
1

If you want to get only ID in array, can use array_map:

    $data = array_map(function($object){
        return $object->ID;
    }, $data);

With that, return an array with ID in every pos.

Ariel Ruiz
  • 163
  • 2
  • 6
1

Its very simple. You can use like this :-

Suppose You have one users table and you want to fetch the id only
$users = DB::table('users')->select('id')->get();
$users = json_decode(json_encode($users)); //it will return you stdclass object
$users = json_decode(json_encode($users),true); //it will return you data in array
echo '<pre>'; print_r($users);

Hope it helps

kunal
  • 4,122
  • 12
  • 40
  • 75
1
$res = ActivityServer::query()->select('channel_id')->where(['id' => $id])->first()->attributesToArray();

I use get(), it returns an object, I use the attributesToArray() to change the object attribute to an array.

Pingolin
  • 3,161
  • 6
  • 25
  • 40
张鹏飞
  • 11
  • 1
0

I suggest you simply do this within your method

public function MyAwesomeMethod($returnQueryAs = null)
{
    $tablename = 'YourAwesomeTable';

    if($returnQueryAs == 'array')
    {
        DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
    }

    return DB::table($tablename)->get();
}

With this all you need is to pass the string 'array' as your argument and Voila! An Associative array is returned.

Dammy
  • 7
  • 3