PHP: Convert Array Notation to Object Notation

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);
Share and Enjoy:
  • Digg
  • del.icio.us
  • Technorati
  • description
  • StumbleUpon
  • Ma.gnolia
  • Design Float
  • Slashdot
  • Facebook
  • BlinkList
  • Furl
  • Reddit
  • NewsVine
  • Mixx
  • Google
  1. Use Object Literals in Javascript
  2. PHP Inheriting From Multiple Objects
  3. PHP: Destroy your objects

Leave your reply
  • (required)
  • (will not be published)
  • Show
    :mrgreen: :neutral: :twisted: :arrow: :shock: :smile: :???: :cool: :evil: :grin: :idea: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad: 8-) 8-O :-( :-) :-? :-D :-P :-o :-x :-| ;-) 8) 8O :( :) :? :D :P :o :x :| ;) :!: :?:
  • Allowed tags: <a href="" title="">, <b>, <i>, <strike>, <em>, <strong>, <code>