PHP - Convert Array to Object with stdClass
The PHP stdClass() is something that isn't well documented but i will try to shed some light into the matter. stdClass is a default PHP object which has no predefined members. The name stdClass is used internally by Zend and is reserved. So that means that you cannot define a class named stdClass in your PHP code.
It can be used to manually instantiate generic objects which you can then set member variables for, this is useful for passing objects to other functions or methods which expect to take an object as an argument. An even more likely usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key in the array.
Here's an example below that converts an array to an object below. This method is called Type Casting.
<?php $person = array ( 'firstname' => 'Richard', 'lastname' => 'Castera' ); $p = (object) $person; echo $p->firstname; // Will print 'Richard' ?>
Here's an example below that converts a multi-dimensional array to an object. This is accomplished through recursion.
<?php
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
?>
<?php
$person = array (
'first' => array('name' => 'Richard')
);
$p = arrayToObject($person);
?>
<?php // Now you can use $p like this: echo $p->first->name; // Will print 'Richard' ?>
Hey Richard, I really like...
Hey Richard, I really like your blog! It's great! Also Google ads are very smoothly integrated.
Thanks!...
Thanks!
$obj = new...
Hi Richard. This is very...
Hi Richard. This is very useful function to convert Array to stdClass object.
Please check out with:
Thanks
Great post! Just discovered...
Great post!
Just discovered that
is faster than
I really like this ... thanks...
I really like this ... thanks
I was looking for something...
I was looking for something like this today and found your blog. While I couldn't get your solution to work (probably because I'm really tired at the moment
but it did inspire me to create my own version which I thought I would share:
Its a little more compact and easier to follow I think. You can also embellish and add in the strtolower and trim for the properties if you like.
Darryl, Thanks for sharing...
Darryl, Thanks for sharing that!
You can also define your own...
You can also define your own class:
Then use it like this:
Great post Richard! I was...
Great post Richard! I was having a problem with a class I needed to serialize to store the value but I needed dynamic variables and stdClass kept erroring out saying:
Fatal error: Cannot access empty propertyIt didn't even occur that I should just create an assoc array and cast it to an object. Thanks for publishing this!
Terri, I'm happy you found...
Terri, I'm happy you found this useful!
Thanks for sharing that!...
Thanks for sharing that!
Tworzenie, Sure!...
Tworzenie, Sure!
Very nice function...
Very nice function indeed,
However I'm having a problem at this moment, it seems that when I call the function to convert an multidimensional associate array, it chops off the first element in the converted stdobject
I'll let you know what I find out.
Chang, Please do. Thanks!...
Chang,
Please do. Thanks!
settype($array,'object');...
JB, Thanks for sharing that!...
JB, Thanks for sharing that!
I too was having the same...
I too was having the same problem as Chang using this code where the first element of an multidimensional associate array was being lost.
The problem is in the test "!empty($name)". If the array uses numeric indices, index zero is considered empty.
I changed "!empty($name)" to "!is_null($name)" and conversion worked as expected.
Interesting, all the samples that I found on the web use the !empty test and would all fail to convert for zero index.
Hope this helps.
Laurie, Thanks for sharing...
Laurie, Thanks for sharing that!
I'm trying to implement this...
I'm trying to implement this with CJ SOAP API, but I think CJ SOAP API is more complicated, I'm still not able to convert stdClass Object to Array.
piwshop, Try reading a couple...
piwshop, Try reading a couple of the comments above, they might have a solution for you.
stdClass is an internal class...
stdClass is an internal class name, not documented and so not recommended to use directly. it might even change in future php versions. instead, you should stick to converting arrays to object, or if you just need a blank object, convert a null to object.
v Who recommends against...
v Who recommends against using stClass? The Zend Framework uses it extensively, and it seems they'd have an inside track on such things.
With all due respect, many...
With all due respect, many frameworks like Drupal will come to a screaming halt if using stdClass directly is disallowed so I think its safe to say that stdClass will be a usable term for the foreseeable future.
Buddy! You are best! I waste...
Buddy! You are best!
I waste 3 hr in looking for this.
Tnx very-very!
Stas,...
Stas,
Hello Richard! Just got here...
Hello Richard!
Just got here from Google, I am currently working on something to do with the Twitter API and that makes a array and stuff. And this just helped me to get the most recent status, I am very grateful, for this! Thank you!
Thank you, that has me very...
Thank you, that has me very helped.
Cool, this is what i was...
Cool, this is what i was looking for.
Man, Your the rock.
I've made a similar solution...
I've made a similar solution and also a php extension that does that:
http://freebsd.co.il/cast/
Very cool, Yury... seems like...
Very cool, Yury... seems like it's throwing a car instead of a wrench at this particular solution, but seeing yours, gave me another idea
. well done!
Hi maybe the following...
Hi maybe the following onliner-function is also a possible solution for some of you. It is part of a static method of a class named 'Type'. So it can be replaced by a global method if needed:
And try to avoid the following mistake. It took me a moment to realize it when I made the mistake. An example:
Make a choice what type of object-properties you want: integer ($oTestInt) or string ($oTestString).
I found out another way. I...
I found out another way. I was looking for a way to reference the array returned from a function and happened on your post. As is turns out it is impossible in PHP to do what I wanted. Well, I FOUND A WORKAROUND, using your post and users' comments I was inspired. It's not elegant and probably has more CPU overhead. Hopefully it helps somebody who is trying to do the same thing I was.
Here's what I wanted to do:
Then I found your post on how to convert arrays to objects thinking that I could:
But that doesn't work in PHP. So finally I came up with:
SUCCESS!! I just don't know why there isn't a function to do this already. Perhaps the powers that be will copy the part of JSON handling that is converting the data to an object and make it into a built-in function. One can only hope. Thx for the post!
Simple and awesome . Thanks...
Simple and awesome . Thanks
Great. Just what I was...
Great. Just what I was looking for, and thanks for the sharing.
What I'm after now, is something that does the reverse, lets me now work with that object as an array.
Works great, thanks!...
Works great, thanks!
Just found this very useful...
Just found this very useful when using WordPress's native database access..
$example = $wpdb->get_results("SELECT * FROM `wp_posts` WHERE ID= '20'");print_r($example);
returns something like
trying to mimic that result from form data was doing my head in.. so thank you
Nice work Richard! Was a...
Nice work Richard! Was a little bit confused about stdClass. Thank you!
It works, Thank you very...
It works, Thank you very much,
..
Hi great post was looking for...
Hi great post was looking for something like this however im stuck as cannot get the recursion properly working....
class config
{
function __construct() {}
function get_objects()
{
return get_object_vars($this);
}
public function make_objects($data)
{
$object = (object) $data;
foreach( $object as $key => $value )
{
if(is_array($value) )
{
$this->$key = (object) $value;//$this->make_objects( $value );
}
else
{
$this->$key = $value;
}
}
}
function test()
{
$arr = array(
'a' => 'test a',
'b' => array(
'b_arr' => 'test b',
'c' => array(
'c_arr' => 'test c'
)
)
);
$this->make_objects($arr);
}
}
if i print_r the config object i get... when not using the recursive method which fine except for the C ARRAY which is expected.
config Object ( [a] => test a [b] => stdClass Object ( [b_arr] => test b [c] => Array ( [c_arr] => test c ) ) )
however when i use the method as recursive i get...
config Object ( [a] => test a [b_arr] => test b [c_arr] => test c [c] => [b] => )
so i love the object after the first array and also adds some crap to the end
any help would be greatly appreciated...
i used ypur code . and add...
i used ypur code .
and add that to my db
:
$array = array(
"title" => "Harry Potter and the Prisoner of Azkaban",
"author" => "J. K. Rowling",
"publisher" => "Arthur A. Levine Books",
"amazon_link" => "http://www.amazon.com/dp/0439136369/"
);
$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";
I'd like to share my solution...
I'd like to share my solution using json with php 5.3 up
<?php
function arrayToObject($data) {
if(is_array($data)) {
$data = json_encode($data);
$data = json_decode($data);
return $data;
}else{
return $data;
}
}
function objectToArray($data){
if(is_array($data)) {
$data = json_encode($data);
$data = json_decode($data,true);
return $data;
}else{
return $data;
}
}
?>
What I always do to preserve...
What I always do to preserve multidimensionality is json_decode(json_encode());
<?php
$array = array("this"=>array("that","this"=>"then","those"),"them","test"=>"that");
print_r(json_decode(json_encode($array)));
?>
Post new comment