- Convert laravel object to array
- 14 Answers 14
- How to convert object of stdClass to array in Laravel
- Php stdClass to array
- The lazy one-liner method
- Converting an array / stdClass -> stdClass
- Converting an array / stdClass -> array
- How to convert object of stdClass to array in Laravel
- Convert stdClass object to array in PHP
- StdClass to array?
- Eloquent return array of stdClass objects?
Convert laravel object to array
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:
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
14 Answers 14
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:
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(. ); >);
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 way
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)
$data=DB::table('table_name')->select(. )->get(); $data=array_map(function($item)< return (array) $item; >,$data);
$data=array_map(function($item)< return (array) $item; >,DB::table('table_name')->select(. )->get());
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,
this worked for me in laravel 5.4
$partnerProfileIds = DB::table('partner_profile_extras')->get()->pluck('partner_profile_id'); $partnerProfileIdsArray = $partnerProfileIds->all();
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" ]
Use the toArray() method to convert an object to array:
$foo = Bar::first(); // Get object $foo = $foo->toArray(); // Convert object to array
It’s also possible to typecast an object to an array. That worked for me here.
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
You need to iterate over the array
ans use (array) conversion because you have array of objects of Std class and not object itself
$users = DB::table('users')->get(); var_dump($users); echo "
"; for ($i = 0, $c = count($users); $i < $c; ++$i) < $users[$i] = (array) $users[$i]; >var_dump($users); exit;
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.
How to convert object of stdClass to array in Laravel
Solution 3: Use the built in type cast functionality, simply type Solution 4: Since it’s an array before you cast it, casting it makes no sense. My view: Solution 1: To convert an object to array (as is your question) use Solution 2: you have hell lot of mistake in your blade file or Solution 3: Try this.. Solution 4: If you getting data is in std class , you can write like this in view page If you getting data is in std class , you can write like this in view page backside write like this Question: I fetch post_id from postmeta as: when i try I have array like this: and i dont know how to traverse it, and how could I get array like this Any idea how can I do this?
Php stdClass to array
I have a problem to convert an object stdclass to array. I have tried in this way:
return (array) json_decode($booking,true);
return (array) json_decode($booking);
The array before the cast is full with one record, after my try to cast it is empty. How to cast / convert it without delete its rows?
array(1) < [0]=>object(stdClass)#23 (36) < ["id"]=>string(1) "2" ["name"]=> string(0) "" ["code"]=> string(5) "56/13" > >
after cast is empty NULL if I try to make a var_dump($booking);
I have also tried this function but always empty:
public function objectToArray($d) < if (is_object($d)) < // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); >if (is_array($d)) < /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); >else < // Return array return $d; >>
The lazy one-liner method
You can do this in a one liner using the JSON methods if you’re willing to lose a tiny bit of performance (though some have reported it being faster than iterating through the objects recursively — most likely because PHP is slow at calling functions). » But I already did this » you say. Not exactly — you used json_decode on the array, but you need to encode it with json_encode first.
Requirements
The json_encode and json_decode methods. These are automatically bundled in PHP 5.2.0 and up. If you use any older version there’s also a PECL library (that said, in that case you should really update your PHP installation. Support for 5.1 stopped in 2006.)
Converting an array / stdClass -> stdClass
$stdClass = json_decode(json_encode($booking));
Converting an array / stdClass -> array
The manual specifies the second argument of json_decode as:
assoc
When TRUE , returned objects will be converted into associative arrays.
Hence the following line will convert your entire object into an array:
$array = json_decode(json_encode($booking), true);
use this function to get a standard array back of the type you are after.
return get_object_vars($booking);
Use the built in type cast functionality, simply type
Since it’s an array before you cast it, casting it makes no sense.
You may want a recursive cast, which would look something like this:
function arrayCastRecursive($array) < if (is_array($array)) < foreach ($array as $key =>$value) < if (is_array($value)) < $array[$key] = arrayCastRecursive($value); >if ($value instanceof stdClass) < $array[$key] = arrayCastRecursive((array)$value); >> > if ($array instanceof stdClass) < return arrayCastRecursive((array)$array); >return $array; >
$obj = new stdClass; $obj->aaa = 'asdf'; $obj->bbb = 'adsf43'; $arr = array('asdf', array($obj, 3)); var_dump($arr); $arr = arrayCastRecursive($arr); var_dump($arr);
Result before:
array 0 => string 'asdf' (length = 4) 1 => array 0 => object(stdClass)[1] public 'aaa' => string 'asdf' (length = 4) public 'bbb' => string 'adsf43' (length = 6) 1 => int 3
Result after:
array 0 => string 'asdf' (length = 4) 1 => array 0 => array 'aaa' => string 'asdf' (length = 4) 'bbb' => string 'adsf43' (length = 6) 1 => int 3
Tested and working with complex arrays where a stdClass object can contain other stdClass objects.
Php — Cannot use object of type stdClass as array in, Browse other questions tagged php arrays laravel laravel-5.5 or ask your own question. The Overflow Blog Satellite internet: More useful than …
How to convert object of stdClass to array in Laravel
I am getting the next error when trying to display a view in Laravel :
«Cannot use object of type stdClass as array (View: C:\xampp\htdocs\mysite\resources\views\cms\contactus.blade.php)».
public function contactus()
class ContactUS extends Model < public $table = 'contactus'; public $fillable = ['name','email','message']; static public function get_content(&$data)< $sql = "SELECT cu.*,name,email,message FROM contactus cu " . "ORDER BY cu.created_at DESC "; $data['contactusd'] = DB::select($sql); >>
To convert an object to array (as is your question) use $array = (array) $object;
you have hell lot of mistake in your blade file
$contactusd = ContactUS::get_content(self::$data)->toArray(); return view('cms.contactus', $contactusd);
$sql = "SELECT cu.*,name,email,message FROM contactus cu " . "ORDER BY cu.created_at DESC "; $data['contactusd'] = DB::select($sql)->get()->toArray();
If you getting data is in std class , you can write like this in view page name >>
If you getting data is in std class , you can write like this in view page >
$sql = "SELECT cu.*,name,email,message FROM contactus cu " . "ORDER BY cu.created_at DESC "; $data['contactusd'] = DB::select($sql)->get()->toArray();
StdClass Object to array in php Code Example, stdClass Object to array in php Code Example // The manual specifies the second argument of json_decode as: // assoc $array = …
Convert stdClass object to array in PHP
I fetch post_id from postmeta as:
$post_id = $wpdb->get_results("SELECT post_id FROM $wpdb->postmeta WHERE (meta_key = 'mfn-post-link1' AND meta_value = '". $from ."')");
when i try print_r($post_id); I have array like this:
Array ( [0] => stdClass Object ( [post_id] => 140 ) [1] => stdClass Object ( [post_id] => 141 ) [2] => stdClass Object ( [post_id] => 142 ) )
and i dont know how to traverse it, and how could I get array like this
Array ( [0] => 140 [1] => 141 [2] => 142 )
Any idea how can I do this?
The easiest way is to JSON-encode your object and then decode it back to an array:
$array = json_decode(json_encode($object), true);
Or if you prefer, you can traverse the object manually, too:
foreach ($object as $value) $array[] = $value->post_id;
Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative.
Take that result and decode with an extra parameter of true, where it will convert to associative array
$array = json_decode(json_encode($oObject),true);
$new_array = objectToArray($yourObject); function objectToArray($d) < if (is_object($d)) < // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); >if (is_array($d)) < /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); >else < // Return array return $d; >>
You can convert an std object to array like this:
$objectToArray = (array)$object;
Php stdClass to array, The lazy one-liner method. You can do this in a one liner using the JSON methods if you’re willing to lose a tiny bit of performance (though some have reported it … Usage example$stdClass = json_decode(json_encode($booking));Feedback
StdClass to array?
stdClass Object ( [0] => stdClass Object ( [one] => aaa [two] => sss ) [1] => stdClass Object ( [one] => ddd [two] => fff ) [2] => stdClass Object ( [one] => ggg [two] => hhh ) >
and i must get this with keys, for example:
Is possible parse this stdClass to array and use this with keys?
If you’re using json_decode to convert that JSON string into an object, you can use the second parameter json_decode($string, true) and that will convert the object to an associative array.
If not, what everybody else has said and just type cast it
Your problem is probably solved since asking, but for reference, quick uncle-google answer:
function objectToArray($d) < if(is_object($d)) < $d = get_object_vars($d); >if(is_array($d)) < return array_map(__FUNCTION__, $d); // recursive >else < return $d; >>
Full article here. Note I’m not associated with the original author in any way.
Arrays — iterating through a stdClass object in PHP, stdclass object ( [_count] => 10 [_start] => 0 [_total] => 37 [values] => array ( [0] => stdclass object ( [_key] => 50180 [group] => stdclass object ( [id] => 50180 …
Eloquent return array of stdClass objects?
Is there a built in way to return an array of standard class objects from an eloquent model instead of an eloquent collection? For example one could do:
return json_decode(json_encode(\App\User::where('status', 'active') ->get()->toArray()));
However this seems like unnecessary overhead since we would be converting the response to an eloquent collection, then to an array, then json encoding that array and then json decoding that string. The reason I am after this functionality is because I am in the process of breaking apart a large enterprise application that was originally created with all business logic within controller methods (which is proving difficult to maintain). I am imposing a standard within the project that all access to the database (using eloquent models and query builder) must be performed in the service class of that particular entity, and that data returned from service classes should be of primitive php types so that if the decision ever comes down to replace eloquent with another orm or swap mysql out completely, these service classes are the only thing that would need to be rewritten to do so (kind of like a repository pattern, but not really since the service classes contain business logic as well as database access via model classes) I suppose one solution to this could be to extend the base eloquent class to contain a method such as toObj() (probably not the best name. good thing I’m not on the standards committee 😉 )