PHP递归文件夹扫描到多数组(子文件夹和文件)

标签 php recursion directory subdirectory

我现在有点迷路了。我的目标是递归扫描包含子文件夹和每个子文件夹中图像的文件夹,将其放入多维数组,然后能够解析每个子文件夹及其包含的图像。

我有以下起始代码,它基本上是扫描包含文件的每个子文件夹,现在只是丢失以将其放入多数组。

$dir = 'data/uploads/farbmuster';
$results = array();

if(is_dir($dir)) {
    $iterator = new RecursiveDirectoryIterator($dir);

    foreach(new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
        if($file->isFile()) {
            $thispath = str_replace('\\','/',$file->getPath());
            $thisfile = utf8_encode($file->getFilename());

            $results[] = 'path: ' . $thispath. ',  filename: ' . $thisfile;
        }
    }
}

有人可以帮我解决这个问题吗?

提前致谢!

最佳答案

你可以试试

$dir = 'test/';
$results = array();
if (is_dir($dir)) {
    $iterator = new RecursiveDirectoryIterator($dir);
    foreach ( new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file ) {
        if ($file->isFile()) {
            $thispath = str_replace('\\', '/', $file);
            $thisfile = utf8_encode($file->getFilename());
            $results = array_merge_recursive($results, pathToArray($thispath));
        }
    }
}
echo "<pre>";
print_r($results);

输出

Array
(
    [test] => Array
        (
            [css] => Array
                (
                    [0] => a.css
                    [1] => b.css
                    [2] => c.css
                    [3] => css.php
                    [4] => css.run.php
                )

            [CSV] => Array
                (
                    [0] => abc.csv
                )

            [image] => Array
                (
                    [0] => a.jpg
                    [1] => ab.jpg
                    [2] => a_rgb_0.jpg
                    [3] => a_rgb_1.jpg
                    [4] => a_rgb_2.jpg
                    [5] => f.jpg
                )

            [img] => Array
                (
                    [users] => Array
                        (
                            [0] => a.jpg
                            [1] => a_rgb_0.jpg
                        )

                )

        )

使用的函数

function pathToArray($path , $separator = '/') {
    if (($pos = strpos($path, $separator)) === false) {
        return array($path);
    }
    return array(substr($path, 0, $pos) => pathToArray(substr($path, $pos + 1)));
}

关于PHP递归文件夹扫描到多数组(子文件夹和文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12974633/

相关文章:

php - Symfony & Paypal = 错误

php - 在 php 中使用 html 和 java 脚本标签

php - 是否可以将 html 添加到 phpinfo 页面?

php - 如何在 php 或 mysql 中查找递归日期?

c# - 我如何获得正确的应用程序目录?

java - 在 Java 7 中,列出带有 "relative path"的文件

python-3.x - 想知道如何删除 Mac 上所有与 python 相关的文件

PHPSECLIB读取目录的总大小?

无重排整数分区的JavaScript递归实现

Java 递归函数有时有效