Created
September 28, 2016 00:55
-
-
Save dasl-/3fb52f7ba325354afc6688b843beb22f to your computer and use it in GitHub Desktop.
print dictionary without recursion
This file contains hidden or 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 | |
$arr = [ | |
"foo" => "bar", | |
"baz" => [ | |
"bang" => "buck", | |
"fuck" => [ | |
"a" => "duck", | |
"for" => [ | |
"welp" => "yeap", | |
"suck" => "much", | |
] | |
] | |
"zomg" => "ukno" | |
], | |
"orly" => "yarly", | |
"fucking" => "shit", | |
]; | |
$stack = []; | |
foreach ($arr as $key => $value) { | |
$stack[] = [$key, $value]; | |
} | |
$stack = array_reverse($stack); | |
$indent_level = 0; | |
while(!empty($stack)) { | |
$top = array_pop($stack); | |
if ($top === true) { | |
$indent_level--; | |
continue; | |
} else { | |
list($key, $value) = $top; | |
} | |
if (is_string($value)) { | |
echo str_repeat(" ", $indent_level) . "$key: $value\n"; | |
} else { | |
echo str_repeat(" ", $indent_level) . "$key:\n"; | |
$indent_level++; | |
$sub_arr = array_reverse($value, true); | |
$stack[] = true; | |
foreach ($sub_arr as $key2 => $value2) { | |
$stack[] = [$key2, $value2]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment