For Programmers: Free Programming Magazines  


Home > Archive > PHP Programming > June 2005 > Convert an associate array to an object?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Convert an associate array to an object?
Robert Oschler

2005-06-09, 3:56 pm

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).

Thanks,
Robert




Andy Hassall

2005-06-09, 8:56 pm

On Thu, 9 Jun 2005 12:59:12 -0400, "Robert Oschler" <no-mail-please@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 / <andy@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2010 codecomments.com