Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Created May 27, 2020 10:58
Show Gist options
  • Select an option

  • Save maheshwaghmare/9d4bca8e18ad23c39b2639a8fa361719 to your computer and use it in GitHub Desktop.

Select an option

Save maheshwaghmare/9d4bca8e18ad23c39b2639a8fa361719 to your computer and use it in GitHub Desktop.
Recursively convert a simple or multidimensional array into object.
<?php
if( ! function_exists( 'prefix_convert_array_to_object' ) ) :
/**
* Convert Array to Object
*
* Recursively convert a simple or multidimensional array into object.
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @param array $data A simple or multidimentional array.
* @since 1.0.0
*
* @return object
*/
function prefix_convert_array_to_object( $data = array() ) {
$object = new stdClass;
if( empty( $data ) ) {
return $object;
}
foreach( $data as $key => $value ) {
if( strlen( $key ) ) {
// Is array then recursively convert itm.
if( is_array( $value ) ) {
$object->{ $key } = prefix_convert_array_to_object( $value );
} else {
$object->{ $key } = $value;
}
}
}
return $object;
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment