Last active
January 24, 2016 01:39
-
-
Save zdenko/9a27b1f228fd8c8a59e3 to your computer and use it in GitHub Desktop.
Function to recursively flatten multidimensional PHP array.
This file contains hidden or 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 flatten_array($arg) { | |
return is_array($arg) ? array_reduce($arg, function ($c, $a) { return array_merge($c, flatten_array($a)); },[]) : [$arg]; | |
} |
This file contains hidden or 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 | |
# Flatten array while preserving keys. | |
# Use custom prefix and / or glue for returned array keys | |
function flatten_assoc_array($arg, $prefix = "", $glue = ".") { | |
$reducer = function ($c, $a) use ($arg, $prefix, $glue) { | |
$_prefix = preg_replace("/^\\{$glue}/", "", "{$prefix}{$glue}{$a}"); | |
return array_merge($c, flatten_assoc_array($arg[$a], $_prefix, $glue)); | |
}; | |
return is_array($arg) ? array_reduce(array_keys($arg), $reducer, []) : array_combine([$prefix], [$arg]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment