php - 文件结构到多维数组

标签 php directory iteration

我需要将所有目录和文件存储在给定位置的多维数组中(示例:/path/to/folder)。无论多深,它都应该包括子文件夹。

已编辑:

我尝试使用 php scandir它给了我以下结果,

代码:

$dir    = '/path/to/folder';
$files = scandir($dir);
print_r($files);

结果:

Array
(
    [0] => .
    [1] => ..
    [2] => folder1
    [3] => file1
    .....
)

我需要的是获取 folder1 中的内容并不断执行此操作,直到获得包含所有文件的完整文件夹结构。

P.S:我需要删除“。”以及结果数组中的“..”。

最佳答案

文件列表 php 提供 readdirscandir功能。

我更喜欢 sccandir,因为它是新的(php 5>),我们可以为此使用以下递归函数。

需要提供目录路径(/path/to/your/folder)作为参数,它将返回具有文件夹结构的多维数组。

function dirToArray($dir) {
    $result = array();
    $cdir = scandir($dir);
    foreach ($cdir as $key => $value) {
        if (!in_array($value,array(".","..")))  {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
                $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
            } else {
                $result[] = $value;
            }
        }
    }
    return $result;
}

关于php - 文件结构到多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18251505/

相关文章:

php - 协助 PHP 和 MySQL 中的搜索功能

vba - 另存为 PDF,在年月文件夹下

excel - 将文件夹链接到 Excel 工作表

c - 在 C 中迭代相同类型的结构成员

c# - 如何在 'for' 循环中从 0.0 正确迭代到 1.0?

python - 如果 `times` 则循环 `times is not None` 否则永远循环

php - 在 Laravel 5.7 中使用 Auth 激活用户 session 时重定向到页面的方法

php - 操作数据的最佳实践

python - Google App Engine yaml 文件配置

php - Laravel Input::file 返回空数组,而 $_FILES 有数据