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

2019-08-24  本文已影响0人  peanut___

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]
上一篇 下一篇

猜你喜欢

热点阅读