Skip to content

Instantly share code, notes, and snippets.

@piercemoore
Created July 13, 2012 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piercemoore/3107841 to your computer and use it in GitHub Desktop.
Save piercemoore/3107841 to your computer and use it in GitHub Desktop.
Convert a multi-dimensional array into an object
<?php
// Full disclosure: I found this solution here: http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass and implemented it both here and in my project.
function arrayToObject( $array ) {
if ( !is_array( $array ) && !is_object( $array ) ) {
return $array;
}
$obj = new stdClass();
if( ( is_array( $array ) || is_object( $array ) ) && count( $array ) > 0 ) {
foreach( $array as $k=>$v ) {
$obj->$k = arrayToObject( $v );
}
return $obj;
} else {
return false;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment