输出所有目录下的文件和子目录下文件树状结构

1 目录结构:

微信截图_20190824174844.png

2 程序以及思路:

  • 获取目标路径
  • 循环目标数组
  • 如果是文件保存到数组
  • 如果是目录再次调用本方法
  • 最后排序
<?php

// 递归
function getFileAndDirectoryNames($path)
{
    $dpath = scandir($path);
    $count = count($dpath);
    $names = [];

    if ($count == 0) return [];
    for ($i = 0; $i < $count; $i++)
    {
        // 过滤
        if ($dpath[$i] != '.' && $dpath[$i] != '..')
        {
            $directory = $path . "/" . $dpath[$i];

            // 是文件
            if (is_file($directory)) $names[] = $dpath[$i];

            // 是目录
            if (is_dir($directory)) $names[$dpath[$i]] = getFileAndDirectoryNames($directory);
        }
    }

    return $names;
}

$file = getFileAndDirectoryNames("../phptest");
asort($file);
print_r($file);

3 结果

Array
(
    [0] => error.txt
    [1] => file.php
    [2] => index.php
    [3] => reg_9.php
    [4] => test.php
    [5] => test.txt
    [6] => user.csv
    [ext] => Array
        (
            [0] => php.ini
            [test] => Array
                (
                    [0] => test.php
                )

            [test1] => Array
                (
                )

        )

)
[Finished in 0.1s]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容