Last active
May 20, 2022 04:25
-
-
Save marcosfreitas/90561da1666c65998c45488f0279bc98 to your computer and use it in GitHub Desktop.
Convert a multidimensional array to object recursively
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
<?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