Skip to content

Instantly share code, notes, and snippets.

@ditikos
Forked from woganmay/squash.php
Created December 1, 2019 15:00
Show Gist options
  • Save ditikos/7d32741b9753400567bb33442776d5bc to your computer and use it in GitHub Desktop.
Save ditikos/7d32741b9753400567bb33442776d5bc 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