Skip to content

Instantly share code, notes, and snippets.

@cetver
Last active August 14, 2016 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cetver/9230799de895a7f89d2b12c28f08f1a9 to your computer and use it in GitHub Desktop.
Save cetver/9230799de895a7f89d2b12c28f08f1a9 to your computer and use it in GitHub Desktop.
php recursive directories render
<?php
/**
* @var $splFileInfo SplFileInfo
*/
$root = '/etc/nginx';
$rdi = new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($rdi);
//$iterator = new RegexIterator($iterator, '/\.txt/', RegexIterator::MATCH);
$tree = [];
foreach ($iterator as $splFileInfo) {
$fileName = $splFileInfo->getFilename();
if ($splFileInfo->isLink() === true) {
$fileName = sprintf('%s -> %s', $fileName, $splFileInfo->getLinkTarget());
}
$children = $splFileInfo->isDir() === false ? [$fileName] : [$fileName => []];
for ($depth = $iterator->getDepth() - 1; $depth >= 0; $depth--) {
$children = [
$iterator->getSubIterator($depth)->current()->getFilename() => $children
];
}
$tree = array_merge_recursive($tree, $children);
}
function sortChildren(&$array)
{
foreach ($array as &$value) {
if (is_array($value) === true) {
sortChildren($value);
}
}
return asort($array);
}
sortChildren($tree);
ksort($tree);
$tree = [
$root => $tree
];
var_dump($tree);
function renderTree($tree, $depth = 0) {
$output = '';
foreach ($tree as $parent => $children) {
if (is_string($parent) === true) {
$output .= '|';
$output .= str_repeat('-', $depth * 2);
$output .= '/';
$output .= ltrim($parent, '/');
$output .= PHP_EOL;
$output .= renderTree($children, $depth + 1);
} else {
$output .= '|';
$output .= str_repeat('-', $depth * 2);
$output .= $children;
$output .= PHP_EOL;
}
}
return $output;
}
printf('<pre>%s</pre>', renderTree($tree));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment