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’
?>

Thanks to {Richard Castera};

About selvam4win

I am Selvam. I am very jolly person and frank one.

Posted on January 19, 2010, in Uncategorized and tagged , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: