Created
August 15, 2013 21:24
-
-
Save clarkf/6245049 to your computer and use it in GitHub Desktop.
A silly little utility for pretty printing multidimensional arrays.
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 | |
| /** | |
| * Recursively print out a multidimensional array | |
| * prettily. Don't use the `$prefix` parameter. | |
| * | |
| * @param array $array The array to print | |
| * @param string $prefix The prefix (internal) | |
| * | |
| * @return string The nice tree | |
| */ | |
| function tree_r(array $array, $prefix = '') | |
| { | |
| // Determine final key | |
| $last_key = end(array_keys($array)); | |
| $buffer = ""; | |
| //var_dump($prefix); | |
| foreach ($array as $key => $value) { | |
| $last = $key == $last_key; | |
| // If its an array, recurse | |
| if (is_array($value)) { | |
| // Buffer the "header" | |
| $buffer .= sprintf( | |
| "%s%s--+ %s\n", | |
| $prefix, | |
| $last ? '`' : '|', | |
| $key | |
| ); | |
| // Buffer the subtree | |
| $buffer .= tree_r( | |
| $value, | |
| $prefix . sprintf('%s ', $last ? ' ' : '|') | |
| ); | |
| } else { | |
| // Pretty print the leaf node | |
| $buffer .= sprintf( | |
| "%s%s- %s\n", | |
| $prefix, | |
| $last ? '`' : '|', | |
| $value | |
| ); | |
| } | |
| } | |
| // Return the buffer | |
| return $buffer; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment