加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-25 08:50:01 所属栏目:PHP 来源:互联网
导读:我现在有点迷失在这里.我的目标是递归扫描每个子文件夹中包含子文件夹和图像的文件夹,将其转换为多维数组,然后能够使用其包含的图像解析每个子文件夹. 我有以下开始代码,它基本上扫描包含文件的每个子文件夹,然后丢失以使其现在进入多数组. $dir = data/uploa

我现在有点迷失在这里.我的目标是递归扫描每个子文件夹中包含子文件夹和图像的文件夹,将其转换为多维数组,然后能够使用其包含的图像解析每个子文件夹.

我有以下开始代码,它基本上扫描包含文件的每个子文件夹,然后丢失以使其现在进入多数组.

$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,$pos) => pathToArray(substr($path,$pos + 1)));
}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读