doudianhuo1129 2019-01-22 08:29
浏览 38

循环遍历目录并使用PHP获取文件并将每个文件夹文件包装在ul li元素中

I have following PHP function which return all the folder with files in html li element from a given path.

function folderTree ($directory_path) {

    if(!file_exists($directory_path)) {
        die("The file $directory_path is not exists");
    }

    if(!is_dir($directory_path)) {
        die("This directory $directory_path can't open");
    }

    $directory = opendir($directory_path);

    $filenames = [];
    while ($filename = readdir($directory)) {
        if($filename !== '.' && $filename !== '..') {
            if(is_dir($directory_path.'/'.$filename)) {
                $filename .= '/';
            }
            $filenames[] = $filename;
        }
    }

    echo "<ul>";
    foreach ($filenames as $filename) {
        echo "<li><a href='{$directory_path}/{$filename}'>";
            echo $filename;
            if(substr($filename, -1) == '/' ) {
                folderTree($directory_path.'/'.substr($filename, 0, -1)).'/lv2/';
            }
        echo "</a></li>";
    }
    echo "</ul>";
}

now It's working fine and the output this below:

img-01  
    img01.jpg    
    img02.jpg    
    img03.jpg    

img-02  
    img01.jpg    
    img02.jpg    
    img03.jpg    

img-03 
    img01.jpg    
    img02.jpg    
    img03.jpg    

This img-01, 02 and 03 is a folder and there are .jpg files exist. Now, You can see the code above that it's wrapping all the files of all folders in a single ul element, right.

But I want it should wrap each folder by folder not all at once.

Now the code output is something like that:

<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li><li>jpg...</li> só on..</ul>

But I need:

<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li></ul>
<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li></ul>
<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li></ul>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器