Monday, December 12, 2011

Turn PHP array into objects - stdClass

Want to access the contents of an array as simple as $array->firtParam

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);
?>

<?php
// Now you can use $p like this:
echo $p->first->name; // Will print 'Richard'
?>
Reference

No comments:

Post a Comment