2010-11-11 105 views
0

我試圖訪問一個嵌套的關聯數組 爲對象嵌套關聯數組對象

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); 

,但它不工作。

請問您能幫我嗎?

在此先感謝。

回答

0

這裏有一個文章,概述如何投下一多維數組的對象:http://www.richardcastera.com/2009/07/06/php-convert-array-to-object-with-stdclass/

+0

$ array =(object)array('user'=> array('data'=> array('name'=>'bob'))); var_dump($ array-> user-> data); ///試圖獲得非對象的屬性在 – Aly 2010-11-11 14:42:00

+0

我可以發誓我以前做過。無論哪種方式,我用別人的解決方案編輯我的答案。 – 2010-11-11 14:54:55

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 
+0

它不起作用 – Aly 2010-11-11 14:43:04