Skip to content

Instantly share code, notes, and snippets.

@clarkf
Created August 15, 2013 21:24
Show Gist options
  • Select an option

  • Save clarkf/6245049 to your computer and use it in GitHub Desktop.

Select an option

Save clarkf/6245049 to your computer and use it in GitHub Desktop.
A silly little utility for pretty printing multidimensional arrays.
<?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