On Thu, 9 Jun 2005 12:59:12 -0400, "Robert Oschler" <no************@nospam.com>
wrote:
With PHP 4, is there a way to convert an associative array to an object?
For example, suppose I have the following arrays inside a nested associative
array ($nestedAA):
$AA1['field1'] = 'fieldValue1';
$AA2['field2'] = 'fieldValue2';
$nestedAA['AA1'] = $AA1;
$nestedAA['AA2'] = $AA2;
I would like to take $nestedAA and convert it to an object called
$nestedObject with properties I could access like this:
echo $nestedObject->AA1->field1; # This would print 'fieldValue1'
echo $nestedObject->AA2->field2; # This would print 'fieldValue2'
How can I do this? Note, I would like a conversion method that I could use
with any nested associativee array and create the object dynamically (at
runtime).
Something like:
<pre>
<?php
$AA1['field1'] = 'fieldValue1';
$AA2['field2'] = 'fieldValue2';
$nestedAA['AA1'] = $AA1;
$nestedAA['AA2'] = $AA2;
var_dump($nestedAA);
function array_to_obj($array, &$obj)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
$obj->$key = new stdClass();
array_to_obj($value, $obj->$key);
}
else
{
$obj->$key = $value;
}
}
return $obj;
}
$nestedObject= new stdClass();
array_to_obj($nestedAA, $nestedObject);
print_r($nestedObject);
echo $nestedObject->AA1->field1; # This would print 'fieldValue1'
echo $nestedObject->AA2->field2; # This would print 'fieldValue2'
?>
</pre>
--
Andy Hassall / <an**@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool