Skip to content

Instantly share code, notes, and snippets.

@matiasvillanueva
Last active June 22, 2017 18:09
Show Gist options
  • Save matiasvillanueva/dce476ecc88501027c0b7e628d916874 to your computer and use it in GitHub Desktop.
Save matiasvillanueva/dce476ecc88501027c0b7e628d916874 to your computer and use it in GitHub Desktop.
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
class Flatten {
/*
* Flatten an array
*
* @param array $a_data Array unflatten
* @return array
*/
public static function array_flatten($array_data){
if (empty($array_data))
return array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array_data));
foreach ($it as $value) {
$result[]=$value;
}
return $result;
}
/*
* Flatten an json array
*
* @param json $json_data Json array unflatten
* @return json
*/
public static function json_flatten($json_data){
return json_encode(self::array_flatten(json_decode($json_data)));
}
}
//Input [[1,2,[3]],4]
$input="[[1,2,[3]],4]";
//Output [1,2,3,4]
echo Flatten::json_flatten($input);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment