-
-
Save paulolorenzobasilio/7e9ab34f888eabd771a47be44066f331 to your computer and use it in GitHub Desktop.
Use PHP to flatten a multidimensional stdClass object (like a json_decode result)
This file contains 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 | |
function squash($array, $prefix = '') | |
{ | |
$flat = array(); | |
$sep = "."; | |
if (!is_array($array)) $array = (array)$array; | |
foreach($array as $key => $value) | |
{ | |
$_key = ltrim($prefix.$sep.$key, "."); | |
if (is_array($value) || is_object($value)) | |
{ | |
// Iterate this one too | |
$flat = array_merge($flat, squash($value, $_key)); | |
} | |
else | |
{ | |
$flat[$_key] = $value; | |
} | |
} | |
return $flat; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment