So do you want to convert an array to an object for no particular reason?
I worked on a project where I wrote this code. The class below eats up to 2536 bytes of memory, but make sure to read this whole post for the surprise!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class array_to_object { 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; } } } } |
The code above creates a new stdClass, PHP’s built-in class and uses it to create properties out of the array’s keys inside the object.
Basically, this $arr['hello'] = ‘world!’; becomes this $arr->hello = ‘world!’;
Now, here comes the surprise!
Hardcore one liner
1 2 3 4 | function array2obj($data) { return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data; } |
The function above does the same thing, except it uses 72 bytes of memory and it’s much more optimized!
Yea, I wanted a way to convert arrays to objects once, and it was fantastic to find that in php all you have to do is cast the array to an object.
Well, not quite, because you have to recursively cast arrays to an object...
The above method works when you have multidimensional arrays too...
the one liner is awesome :)
@Can Berkol: Yep, a guy told me on a forum... you can do pretty amazing optimizations :P
geez..the one liner is sick.