Reputation: 1816
I'm trying to construct a function that will echo out an unordered list of all sub-directories and files from a URL.
I know there's quite a few examples here on this, but I'm struggling to find something appropriate.
This is what I have so far:
$dir = "an/example/directory";
echo "<ul id='folderList'>";
$dirArr = dirToArray($dir);
listDir($dirArr);
echo "</ul>";
The first function recursively searches for files and folders and sorts them into a multidimensional array:
function dirToArray($dir)
{
$result = array();
$cdir = scandir($dir);
foreach($cdir as $key => $value) {
if (!in_array($value, array(".", ".."))) {
if(is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
$result[$dir . DIRECTORY_SEPARATOR . $value] = $this->dirToArray($dir . DIRECTORY_SEPARATOR . $value);
} else {
$result[$dir . DIRECTORY_SEPARATOR . $value] = $dir . DIRECTORY_SEPARATOR . $value;
}
}
}
return $result;
}
Now this is the part I'm having trouble with. The second function should loop through the multi-array and echo out its contents accordingly.
function listDir($multiArr)
{
foreach ($multiArr as $key => $value) {
if (is_array($value)) {
echo '<li class="sub-directory"><span>'.basename($key).'</span>';
echo '<ul>';
listDir($multiArr[$key]);
echo '</ul>';
} else {
echo '<li class="file"><span>'.basename($value).'</span>';
}
echo '</li>';
}
}
However this second function doesn't seem to be working as expected. I'm not really sure why, but it seems to have trouble with recursively looping properly.
Anyway the idea is that once the two functions are run, the output should look this:
<ul id='folderList'>
<li class="sub-directory"><span>sub-directory-name</span>
<ul>
<li class="file><span>fileName1</span></li>
<li class="file><span>fileName2</span></li>
</ul>
</li>
<li class="file><span>fileName3</span></li>
</ul>
Upvotes: 2
Views: 1143
Reputation: 57
you can use the bekow function to list in table format ...
function dirToArray($dir)
{
$cdir = scandir($dir);
echo "<table>";
foreach ($cdir as $key => $value)
{
echo "<tr>";
if (!in_array($value, array(".")))
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
{
$path = $dir . DIRECTORY_SEPARATOR . $value;
echo "<td><a href='file_name.php?dir=$path' >" . $value . "</a></td>";
}
else
{
$path = $dir . DIRECTORY_SEPARATOR . $value;
echo "<td></td><td><a>". $value . "</a></td>";
}
}
echo "</tr>";
}
echo "</table>";
}
dirToArray($dir);
Upvotes: 1
Reputation: 703
Here is the simple function to get Main directory and sub directory
function listdir($dir){
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li>'.$ff;
if(is_dir($dir.'/'.$ff)) listdir($dir.'/'.$ff);
echo '</li>';
}
}
echo '</ol>';
}
listdir('Main Dir');
Upvotes: 2