You are here: Re: Convert an associate array to an object? « PHP Programming Language « IT news, forums, messages
Re: Convert an associate array to an object?

Posted by Andy Hassall on 06/09/05 23:27

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

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация