本文介绍了PHP-递归数组到对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在PHP中是否可以将多维array
转换为stdClass
对象?
Is there a way to convert a multidimensional array
to a stdClass
object in PHP?
铸造为(object)
似乎没有递归工作. json_decode(json_encode($array))
产生我想要的结果,但是必须有更好的方法...
Casting as (object)
doesn't seem to work recursively. json_decode(json_encode($array))
produces the result I'm looking for, but there has to be a better way...
推荐答案
据我所知,目前还没有预构建的解决方案,因此您可以自己动手:
As far as I can tell, there is no prebuilt solution for this, so you can just roll your own:
function array_to_object($array) {
$obj = new stdClass;
foreach($array as $k => $v) {
if(strlen($k)) {
if(is_array($v)) {
$obj->{$k} = array_to_object($v); //RECURSION
} else {
$obj->{$k} = $v;
}
}
}
return $obj;
}
这篇关于PHP-递归数组到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!