Nested associative array as object
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->开发者_如何学Cdata);
but it doesn't work.
Could you help me, please ?
Thanks in advance.
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
Here's an article outlining how to cast a multi dimensional array to an object: http://www.richardcastera.com/2009/07/06/php-convert-array-to-object-with-stdclass/
how about
json_decode(json_encode($array_instance))
https://meet.google.com/linkredirect?authuser=0&dest=http%3A%2F%2Fsandbox.onlinephpfunctions.com%2Fcode%2Fd15d52ae1b110f50d4d8a1b9c3d67f45c2565a56
精彩评论