如何在PHP中将多维数组转换为对象? [英] how to convert multidimensional array to object in php?

查看:690
本文介绍了如何在PHP中将多维数组转换为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组:

$image_path = array('sm'=>$sm,'lg'=>$lg,'secondary'=>$sec_image);

女巫看起来像这样:

[_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.

有什么想法吗?

谢谢

$obj = (object)$image_path;似乎不起作用.我需要一种遍历数组并创建对象的不同方式

edit: $obj = (object)$image_path; doesn't seem to work. i need a different way of looping through the array and creating a object

推荐答案

一种快速的方法是:

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

说明

json_encode($array)会将整个多维数组转换为JSON字符串. ( php.net/json_encode )

json_encode($array) will convert the entire multi-dimensional array to a JSON string. (php.net/json_encode)

json_decode($string)将JSON字符串转换为stdClass对象.如果将TRUE作为第二个参数传递给json_decode,则会得到一个关联数组. ( php.net/json_decode )

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.

这篇关于如何在PHP中将多维数组转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆