Last active
March 30, 2018 14:23
-
-
Save kevinfiol/941b9a3c0df52984b362b42fbc6d642c to your computer and use it in GitHub Desktop.
Flatten Multi-Dimensional PHP Arrays
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 | |
function flatten($arr, $keys = []) { | |
$res = []; | |
foreach ($arr as $key => $val) { | |
$keys[] = strval($key); | |
if (is_array($val)) { | |
$res = array_merge($res, flatten($val, $keys)); | |
} else { | |
$res['_' . implode('.', $keys)] = $val; | |
} | |
array_pop($keys); | |
} | |
return $res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Input:
Sample Output: