Skip to content

Instantly share code, notes, and snippets.

@paulolorenzobasilio
Forked from woganmay/squash.php
Created May 5, 2021 05:57
Show Gist options
  • Save paulolorenzobasilio/7e9ab34f888eabd771a47be44066f331 to your computer and use it in GitHub Desktop.
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)
<?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