Skip to content

Instantly share code, notes, and snippets.

@cosminpopescu14
Forked from woganmay/squash.php
Created May 30, 2018 14:06
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 cosminpopescu14/1e8488fc0db56a32f36b3377e89ce8f3 to your computer and use it in GitHub Desktop.
Save cosminpopescu14/1e8488fc0db56a32f36b3377e89ce8f3 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