Last active
August 29, 2015 14:15
-
-
Save lin/14b7f22ad8949f9a2866 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function arrayToObject_recursive ( $data, $key = NULL) { | |
| // 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 if (array_key_exists("_id", $data)) { | |
| $class = ucwords($key); | |
| } 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, $key ); | |
| }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, $key ); | |
| } | |
| // finally, return the structure. | |
| return $result; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Foo { | |
| public $aMemberVar = 'aMemberVar Member Variable'; | |
| public $aFuncName = 'aMemberFunc'; | |
| function aMemberFunc() { | |
| print 'Inside `aMemberFunc()`'; | |
| } | |
| } | |
| $arr1 = array( | |
| "bar" => Array("foo", "bar"), | |
| "foobar" => Array("foo", "bar" => Array("foo"=>"bar", "bar"=>"foo")), | |
| "foo" => Array("_id" => "bar", "bar" => "foo"), | |
| "_model_class" => "stdClass" | |
| ); | |
| $object1 = arrayToObject_recursive($arr1); | |
| echo(get_class($object1->foo)); | |
| var_dump($object1->foo->bar); | |
| $object1->foo->aMemberFunc(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment