PHP array of folders in directory and show files in each folder

爱⌒轻易说出口 提交于 2019-12-12 05:04:16

问题


I am using the following code to list all folders in a directory (called test), and all files within those folders:

<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
    if($ff != '.' && $ff != '..'){
        echo '<li class="title">'.$ff;
        if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
        echo '</li>';
    }
}
echo '</ol>';
}

listFolderFiles('test');

?>

This works fine, however I want to be able to link to each file in those folders. Can anyone tell me how I would do this?

For example I have a directory called "test" with subdirectories "test 1", "test 2" and "test 3". In each of those I have a couple of files that I would like to be links that a user can click on to show the file. So when a user goes to the site they will see something like this:

Test 1: link 1 link 2

Test 2: link 1 link 2

Test 3: link 1 link 2


回答1:


Just add a html A tag inside the LI tag you are outputting. Something along these lines should work:

<?php
function listFolderFiles($dir){
    $ffs = scandir($dir);
    echo '<ol>';
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            echo '<li class="title">';
            if(is_dir($dir.'/'.$ff)){
                echo $ff;
                listFolderFiles($dir.'/'.$ff);
            }else{
                echo '<a href="'.$dir.'/'.$ff.'">'.$ff.'</a>';
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}


listFolderFiles('test');

?>


来源:https://stackoverflow.com/questions/15876455/php-array-of-folders-in-directory-and-show-files-in-each-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!