Pat*_*cow 17 php object multidimensional-array
我有一个多维数组:
$image_path = array('sm'=>$sm,'lg'=>$lg,'secondary'=>$sec_image);
Run Code Online (Sandbox Code Playgroud)
女巫看起来像这样:
[_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
)
)
Run Code Online (Sandbox Code Playgroud)
我想将其转换为一个对象并保留关键名称.
有任何想法吗?
谢谢
编辑:$obj = (object)$image_path;似乎不起作用.我需要一种不同的循环数组和创建对象的方式
Cha*_*ser 95
一个快速的方法是:
$obj = json_decode(json_encode($array));
Run Code Online (Sandbox Code Playgroud)
说明
json_encode($array)将整个多维数组转换为JSON字符串.(php.net/json_encode)
json_decode($string)将JSON字符串转换为stdClass对象.如果你TRUE作为第二个参数传入json_decode,你将得到一个关联数组.(php.net/json_decode)
我不认为这里的性能与递归通过数组并转换所有内容都非常明显,尽管我希望看到一些这方面的基准.它有效,它不会消失.
如果您有能力,最好的方法是从一开始就将数据结构作为对象进行管理:
$a = (object) array( ... ); $a->prop = $value; //and so on
Run Code Online (Sandbox Code Playgroud)
但最快的方法是使用@CharlieS提供的方法json_decode(json_encode($a)).
您还可以通过递归函数运行数组来完成相同的操作.我没有对json方法进行基准测试,但是:
function convert_array_to_obj_recursive($a) {
if (is_array($a) ) {
foreach($a as $k => $v) {
if (is_integer($k)) {
// only need this if you want to keep the array indexes separate
// from the object notation: eg. $o->{1}
$a['index'][$k] = convert_array_to_obj_recursive($v);
}
else {
$a[$k] = convert_array_to_obj_recursive($v);
}
}
return (object) $a;
}
// else maintain the type of $a
return $a;
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
编辑:json_encode + json_decode将根据需要创建一个对象.但是,如果数组是数字或混合索引(例如array('a', 'b', 'foo'=>'bar')),您将无法使用对象表示法引用数字索引(例如$ o-> 1或$ o [1]).上面的函数将所有数字索引放入'index'属性中,该属性本身就是一个数值数组.那么,你就能做到$o->index[1].这样可以保持已转换数组与已创建对象的区别,并保留选项以合并可能具有数字属性的对象.
| 归档时间: |
|
| 查看次数: |
22018 次 |
| 最近记录: |