PHP: Convert Array Notation to Object Notation
September 29th, 2007
Update:
Here is a hardcore one-liner from a forum posting (thanks man). It seems I wasted my time for nothing…again…
function array2obj($data) {
return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data;
}
$data = array();
$data['db']['def']['host'] = 'localhost';
$data['db']['def']['username'] = 'username';
$data['db']['def']['pw'] = 'password';
var_dump(array2obj($data));
And still if you want a more elegant version of it read on. This code above takes up 72 in memory, mine 2536. Yeah sweet…
I spent a whole day figuring out how to do this. Converting and array to an object. Object notation to be more precise.
Here’s an example:
I want this:
$data['db']['default']['host'] = 'localhost'; $data['db']['default']['username'] = 'root';
Converted to this
$data->db->default->host; $data->db->default->username;
Then I found stdClass(). And with a little ‘recursive class’ I finally coded the stuff. Here it is:
class objArray
{
function __construct($data=null, &$node=null)
{
foreach ( $data as $key => $value )
{
if ( is_array($value) )
{
if (! $node )
{
$node =& $this;
}
$node->$key = new stdClass();
self::__construct($value,$node->$key);
}
else
{
if (! $node )
{
$node =& $this;
}
$node->$key = $value;
}
}
}
}
$data = array();
$data['node1'] ['subnode1'] = 'node1-subnode1';
$data['node1'] ['subnode2'] = 'node1-subnode2';
$data['node2'] ['subnode1'] = 'node2-subnode1';
$data['node2'] ['subnode2'] = 'node2-subnode2';
$obj = new objArray($data);
var_dump($obj);

















Leave your reply