public
Last active

Convert a multi-dimensional array into an object

  • Download Gist
arrayToObject.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?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;
}
}
 
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.