嵌套关联数组作为对象

时间:2010-11-11 14:23:41

标签: php

我正在尝试访问嵌套的关联数组 作为对象

function multiArrayToObject(array $array){

   if(!is_string(key($array))){
        throw new Exception('Invalid associative array'); 
    }
    $root = new ArrayObject($array,ArrayObject::ARRAY_AS_PROPS);
    foreach($array as $value){
       if(is_array($value)){
            multiArrayToObject($value);
       }
       else{
            return $root;
       }
    }
    return $root;
}

$array = array('user' => array('data'=>array('name'=>'bob')));


$data = multiArrayToObject($array);



var_dump($data->user->data);

但它不起作用。

请问你能帮帮我吗?

提前致谢。

3 个答案:

答案 0 :(得分:0)

这是一篇概述如何将多维数组转换为对象的文章:http://www.richardcastera.com/2009/07/06/php-convert-array-to-object-with-stdclass/

答案 1 :(得分:0)

我不知道为什么你会想要这个,但我认为这应该解决它:

foreach($array as &$value){ // $value needs to be a reference to be able to change it
   if(is_array($value)){
        $value = multiArrayToObject($value); // you need to store the result
   }
   else{
        return $root; // i left this in, i'm not sure what it's for
   }
} unset($value); // this is recommended because of the & above

答案 2 :(得分:0)