Skip to content

Instantly share code, notes, and snippets.

@bishwanathjha
Created May 30, 2021 17:01
Show Gist options
  • Save bishwanathjha/9ea05898a8f1846f61be1d87ebf3e4be to your computer and use it in GitHub Desktop.
Save bishwanathjha/9ea05898a8f1846f61be1d87ebf3e4be to your computer and use it in GitHub Desktop.
PRAMP Flatten a Dictionary in PHP
<?php
$list = [];
function flatten($array) {
global $list;
foreach ($array as $key => $value) {
utility($value, $key);
}
return $list;
}
function utility($array, $prefix) {
global $list;
if(is_scalar($array)) {
$list[$prefix] = $array;
return $list;
}
foreach ($array as $key => $value) {
$newKey = !empty($key) ? ($prefix . "." . $key) : $prefix;
utility($value, $newKey);
}
return $list;
}
$array = [
'name' => 'Bishwanath',
'last_name' => 'kumar',
'profession' => 'Engineer',
'traits' => [
'intell' => true,
'exp' => [
'2010' => 'college',
'2014' => 'employed',
'2016' => [
'may' => 'test 1',
'june' => 'test 2'
],
"" => [
"a" => "b"
]
]
]
];
print_r(flatten($array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment