Created
March 4, 2016 11:24
-
-
Save gwarnants/cfe08f5fce8905e5618a to your computer and use it in GitHub Desktop.
Flatten a multidimensional array to a single dimensional array by joining nested keys together
This file contains 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 a multidimensional array to a single dimensional array by joining nested keys together | |
* | |
* @param array $array The array to flatten | |
* @param string $glue Glue string to join keys together | |
* @return array | |
*/ | |
function array_linearize(array $array, $glue = '/') | |
{ | |
$output = array(); | |
foreach ($array as $k => $v) { | |
if (is_array($v)) { | |
foreach (array_linearize($v, $glue) as $k2 => $v2) { | |
$output[$k.$glue.$k2] = $v2; | |
} | |
} else { | |
$output[$k] = $v; | |
} | |
} | |
return $output; | |
} | |
/** | |
* Example : | |
* | |
* Array | |
* ( | |
* [0] => 0 | |
* [foo] => bar | |
* [nested] => Array | |
* ( | |
* [0] => 0 | |
* [foo] => bar | |
* [nested] => Array() | |
* ) | |
* ) | |
* | |
* will give : | |
* | |
* Array | |
* ( | |
* [0] => 0 | |
* [foo] => bar | |
* [nested/0] => 0 | |
* [nested/foo] => bar | |
* ) | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment