Convert laravel object to array
Asked Answered
K

14

34

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

Krohn answered 3/10, 2014 at 6:32 Comment(3)
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 arrayTribulation
yes it came from DB..Krohn
Duplicate question? #28659391Nona
H
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(...);
});
Harvester answered 3/10, 2014 at 7:25 Comment(4)
I think you should add to your question this will change fetch mode for all queries not only for this one. But nice to know it can be also changed this wayConfidential
Yes, it will affect all the queries for this request unless you revert it. Edited to make it clear.Harvester
you can also edit config/database.php, replace 'fecth' => PDO::FETCH_CLASS to PDO::FETCH_ASSOCTijuanatike
This no longer work on new laravel since version 5.4 They scrap this awayAssuan
C
46
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

Choleric answered 3/10, 2014 at 21:50 Comment(0)
H
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(...);
});
Harvester answered 3/10, 2014 at 7:25 Comment(4)
I think you should add to your question this will change fetch mode for all queries not only for this one. But nice to know it can be also changed this wayConfidential
Yes, it will affect all the queries for this request unless you revert it. Edited to make it clear.Harvester
you can also edit config/database.php, replace 'fecth' => PDO::FETCH_CLASS to PDO::FETCH_ASSOCTijuanatike
This no longer work on new laravel since version 5.4 They scrap this awayAssuan
L
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);
}
Lactalbumin answered 19/4, 2018 at 3:19 Comment(0)
C
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());
Conurbation answered 29/1, 2015 at 11:45 Comment(0)
B
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.

Benzoin answered 3/10, 2014 at 6:54 Comment(0)
S
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

Smtih answered 22/3, 2018 at 10:13 Comment(0)
S
6

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

$foo = Bar::first(); // Get object
$foo = $foo->toArray(); // Convert object to array
Slav answered 13/11, 2018 at 18:38 Comment(0)
C
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 }}
Contortionist answered 18/11, 2019 at 4:23 Comment(0)
F
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.

Frambesia answered 3/10, 2014 at 6:34 Comment(5)
i tried both methods.. same error Call to a member function toArray() on a non-object Krohn
@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 conversionConfidential
Iam getting data from laravel database ... it uses std class ...data is exactly same....Krohn
If you're using Laravel properly, it uses model objects and collections, not StdClass objectsLitter
@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)Harvester
C
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)
}
Castleberry answered 5/10, 2020 at 6:12 Comment(0)
U
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.

Unutterable answered 15/9, 2017 at 17:42 Comment(0)
A
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

Argentinaargentine answered 10/3, 2018 at 5:5 Comment(0)
A
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.

Amati answered 25/4, 2019 at 5:59 Comment(0)
U
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.

Unconstitutional answered 21/11, 2014 at 20:39 Comment(1)
There is an unnecessary quote mark in the end of first line and that breaks the formatting.Inspirational

© 2022 - 2024 — McMap. All rights reserved.