Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

how to convert multidimensional array to object in php?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A quick way to do this is:

$obj = json_decode(json_encode($array));

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 a stdClass object. If you pass in TRUE as a second argument to json_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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...