Skip to content

Instantly share code, notes, and snippets.

@gwarnants
Created March 4, 2016 11:24
Show Gist options
  • Save gwarnants/cfe08f5fce8905e5618a to your computer and use it in GitHub Desktop.
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
<?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