Created
May 30, 2021 17:01
-
-
Save bishwanathjha/9ea05898a8f1846f61be1d87ebf3e4be to your computer and use it in GitHub Desktop.
PRAMP Flatten a Dictionary in PHP
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 | |
$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