Skip to content

Instantly share code, notes, and snippets.

@lin
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save lin/42b67a894b9917fee175 to your computer and use it in GitHub Desktop.

Select an option

Save lin/42b67a894b9917fee175 to your computer and use it in GitHub Desktop.
function arrayToObject_recursive ( $data ) {
// if the passed data is just a value, return it, and terminate the recursion.
if ( !is_array( $data ) )
return $data;
// otherwise, read the class name out of the data.
if ( array_keys($data) !== range(0, count($data) - 1) ) {
if ( !empty( $data['_model_class'] ) ) {
$class = $data['_model_class'];
} else {
$class = "stdClass";
}
// instantiate an object of the found class.
$result = new $class;
// then recursively parse it's values, and add them as fields on the object.
foreach ($data as $key => $value)
$result->$key = arrayToObject_recursive( $value );
}else{
// if no class name could be found, treat it as just a raw array.
$result = array();
// then recursively parse it's values, and add them as fields on the object.
foreach ($data as $key => $value)
$result[$key] = arrayToObject_recursive( $value );
}
// finally, return the structure.
return $result;
}
$arr1 = array(
"foo" => "bar",
"bar" => Array("foo", "bar"),
"barfoo" => Array("foo" => "bar", "bar" => "foo"),
"_model_class" => "stdClass"
);
$arr2 = array(
"foo" => "bar",
"bar" => Array("foo", "bar"),
"barfoo" => Array("foo" => "bar", "bar" => "foo"),
);
$object1 = arrayToObject_recursive($arr1);
$object2 = arrayToObject_recursive($arr2);
var_dump($object1->foo);
var_dump($object1->bar[0]);
var_dump($object1->barfoo->bar);
echo(get_class($object1));
var_dump($object2->foo);
var_dump($object2->bar[0]);
var_dump($object2->barfoo->bar);
echo(get_class($object2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment