Skip to content

Instantly share code, notes, and snippets.

@marcosfreitas
Last active May 20, 2022 04:25
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 marcosfreitas/90561da1666c65998c45488f0279bc98 to your computer and use it in GitHub Desktop.
Save marcosfreitas/90561da1666c65998c45488f0279bc98 to your computer and use it in GitHub Desktop.
Convert a multidimensional array to object recursively
<?php
/**
* Convert a multidimensional array to an object recursively.
* For any arrays inside another array, the result will be an array of objects.
*
* @author Marcos Freitas
* @param array|any $props
* @return array|any
*/
function array_to_object($props, $preserve_array_indexes = false) {
$obj = new \stdClass();
if (!is_array($props)) {
return $props;
}
foreach($props as $key => $value) {
if (is_numeric($key) && !$preserve_array_indexes) {
if(!is_array($obj)) {
$obj = [];
}
$obj[] = $this->array_to_object($value);
continue;
}
$obj->{$key} = is_array($value) ? $this->array_to_object($value) : $value;
}
return $obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment