i have a multidimensional array:
$image_path = array('sm'=>$sm,'lg'=>$lg,'secondary'=>$sec_image);
witch looks like this:
[_media_path:protected] => Array
(
[main_thumb] => http://example.com/e4150.jpg
[main_large] => http://example.com/e4150.jpg
[secondary] => Array
(
[0] => http://example.com/e4150.jpg
[1] => http://example.com/e4150.jpg
[2] => http://example.com/e9243.jpg
[3] => http://example.com/e9244.jpg
)
)
and i would like to convert it into an object and retain the key names.
Any ideas?
Thanks
edit: $obj = (object)$image_path; doesn’t seem to work. i need a different way of looping through the array and creating a object
A quick way to do this is:
Explanation
json_encode($array)will convert the entire multi-dimensional array to a JSON string. (php.net/json_encode)json_decode($string)will convert the JSON string to astdClassobject. If you pass inTRUEas a second argument tojson_decode, you’ll get an associative array back. (php.net/json_decode)I don’t think the performance here vs recursively going through the array and converting everything is very noticeable, although I’d like to see some benchmarks of this. It works, and it’s not going to go away.