Here's how you do it
<?php
$person = array (
'firstname' => 'Richard',
'lastname' => 'Castera'
);
$p = (object) $person;
echo $p->firstname; // Will print 'Richard'
?>
Multi-dimensional array example
<?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);
?>
Reference
<?php
// Now you can use $p like this:
echo $p->first->name; // Will print 'Richard'
?>
No comments:
Post a Comment