I'm trying to access a nested associative array as object
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);
but it doesn't work.
Could you help me, please ?
Thanks in advance.
这是一篇概述如何将多维数组转换为对象的文章: http : //www.richardcastera.com/2009/07/06/php-convert-array-to-object-with-stdclass/
I don't know why you would want this, but I think this should fix it:
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
how about
json_decode(json_encode($array_instance))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.