Created
November 14, 2013 21:47
-
-
Save mmohiudd/7474896 to your computer and use it in GitHub Desktop.
Flatten a multidimensional array with keys separated by _
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
/** | |
* Flatten a multi dimension array. For an associative array the child keys are separated by underscore(_). | |
* @author Muntasir Mohiuddin | |
* @param array $a multidimensional array to flatten | |
* @param array $a multidimensional array to save values | |
* @param string $p previous parents separated by underscore(_) | |
* @return array all flattened keys | |
*/ | |
function flatten_array($a, &$r, $p=NULL){ | |
foreach($a as $k => $v) { | |
$keys[] = $k; | |
if(is_null($p)){ | |
$_p = $k; | |
} else { | |
$_p = $p . "_" . $k; | |
} | |
if (is_array($a[$k])) { | |
$keys = array_merge($keys, flatten_array($a[$k], $r, $_p)); | |
} else { | |
$r[$_p] = $v; | |
} | |
} | |
return $keys; | |
} | |
$property_value = array( | |
'a' => 'VALUE A', | |
'b' => 'VALUE B', | |
'c' => array( | |
'd' => 'VALUE d', | |
'e' => 'VALUE E', | |
'f' => array( | |
'g' => 'VALUE G' | |
), | |
), | |
'h' => 'VALUE H', | |
'i' => array( | |
'j' => 'VALUE J', | |
'k' => array( | |
'l' => 'VALUE L', | |
'm' => array( | |
'n' => 'VALUE n', | |
), | |
), | |
), | |
); | |
$flatten_values = array(); | |
flatten_array($property_value, $flatten_values); | |
/* OUTPUT | |
Array | |
( | |
[a] => VALUE A | |
[b] => VALUE B | |
[c_d] => VALUE d | |
[c_e] => VALUE E | |
[c_f_g] => VALUE G | |
[h] => VALUE H | |
[i_j] => VALUE J | |
[i_k_l] => VALUE L | |
[i_k_m_n] => VALUE n | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment