Skip to content

Instantly share code, notes, and snippets.

@ohader
Created April 5, 2018 16:20
Show Gist options
  • Save ohader/4f746a8f99b0e119ef88ff4954ab8b98 to your computer and use it in GitHub Desktop.
Save ohader/4f746a8f99b0e119ef88ff4954ab8b98 to your computer and use it in GitHub Desktop.
<?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