Created
April 5, 2018 16:20
-
-
Save ohader/4f746a8f99b0e119ef88ff4954ab8b98 to your computer and use it in GitHub Desktop.
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 | |
/* | |
Result: | |
Array | |
( | |
[foo.bar] => | |
[foo.down.a] => AA | |
[foo.down.b] => BB | |
[value] => test | |
) | |
*/ | |
$array = [ | |
'foo' => [ | |
'bar' => '', | |
'down' => [ | |
'a' => 'AA', | |
'b' => 'BB', | |
], | |
], | |
'value' => 'test', | |
]; | |
function flat(array $array, string $prefix = ''): array | |
{ | |
$result = []; | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
$result = array_merge( | |
$result, | |
flat($value, $prefix . $key . '.') | |
); | |
} else { | |
$result[$prefix . $key] = $value; | |
} | |
} | |
return $result; | |
} | |
var_dump(flat($array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment