Skip to content

Instantly share code, notes, and snippets.

@twodayslate
Last active August 29, 2015 14:08
Show Gist options
  • Save twodayslate/b24f3e0487965544c1ce to your computer and use it in GitHub Desktop.
Save twodayslate/b24f3e0487965544c1ce to your computer and use it in GitHub Desktop.
PHP directory traversal tree
<?php
$array = array();
$lastDepth = 0;
$dirStack = array();
foreach ($iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("./",
RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST) as $item) {
// Note SELF_FIRST, so array keys are in place before values are pushed.
$currentDepth = $iterator -> getDepth();
$subPath = $iterator->getSubPathName();
//$value = preg_rdeplace("~".end($dirStack)."/~", "", $subPath, 1);
if($item->isDir()) {
// Create a new array key of the current directory name.
$array[$subPath] = array();
$lastDepth = $currentDepth;
$dirStack[] = $subPath;
}
else {
// Add a new element to the array of the current file name.
//$array[] = $subPath;
if($lastDepth > $currentDepth) {
$lastDepth = $currentDepth;
array_pop($dirStack);
} else {
switch(count($dirStack)) {
case 1: {
$value = preg_replace("/".end($dirStack)."/", "", $subPath, 1);
$array[end($dirStack)][] = $value;
break;
}
case 2: {
$realPath = preg_replace("~".$iterator->getSubPath()."~", "", $subPath, 1);
$realPath = end($dirStack).$realPath;
$array[$dirStack[0]][end($dirStack)][] = $realPath;
break;
}
case 3: {
$realPath = preg_replace("~".$iterator->getSubPath()."~", "", $subPath, 1);
$realPath = end($dirStack).$realPath;
$array[$dirStack[0]][$dirStack[1]][end($dirStack)][] = $realPath;
break;
}
default: $array[] = $subPath;
}
}
}
}
unset($array[0]);
$array = array_filter($array);
function printDir($array, $k = null) {
foreach ($array as $key => $item) {
if(is_array($item)) {
$name = preg_replace("~".$k."~", "", $key, 1);
$name = preg_replace("~/~", "", $name, 1);
echo "<li><a href=\"./".$key."\">".$name."</a></li><ul>";
printDir($item, $key);
echo "</ul>";
} else {
$value = $item;
$name = preg_replace("~".$k."~", "", $item, 1);
$name = preg_replace("~/~", "", $name, 1);
echo "<li><a href=\"./".$item."\">".$name."</a></li>";
}
}
}
?>
<!-- to show tree -->
<ul>
<?php printDir($array); ?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment