问题
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