简体   繁体   English

查找目录/子目录中的所有文件并将它们分组在一个数组中?

[英]Find all files within directory/sub-directory and group them in an array?

I'm writing a script that matches a list of items with an image, which is stored in a folder and possibly sub-folders of this main folder. 我正在编写一个脚本,该脚本将带有图像的项目列表与之匹配,该图像存储在一个文件夹中,并且可能存储在此主文件夹的子文件夹中。 I want to take all files within the main/sub-folders and put them in an array. 我想将主/子文件夹中的所有文件都放入一个数组中。

I have a function which finds all files but doesn't lump them in a single array (so that I can easily match the item with image - it is much harder if its multi-dimensional). 我有一个函数,它可以找到所有文件,但不会将它们集中在一个数组中(这样我就可以轻松地将项目与图像进行匹配-如果它是多维的,则要困难得多)。

function listFolderFiles($dir){
    $ffs = scandir($dir);
    echo '<ol>';
    $images = [];
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            echo '<li>'.$ff;
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            echo '</li>';
            $images[] = $ff;
        }
    }
    echo "<pre>";
    print_r($images);
    echo '</ol>';
}

listFolderFiles("K:\\");

Any ideas on how I can do flatten the resultant array? 关于如何使结果数组变平的任何想法?

To return an array instead of printing the HTML, you will obviously remove the echo commands. 要返回一个数组而不是打印HTML,显然您将删除echo命令。

First, define the array at the beginning of the function, such as $return = array(); 首先,在函数的开头定义数组,例如$ return = array();。

Now, instead of echoing $ff, you use $return[] = $ff; 现在,不用回显$ ff,而是使用$ return [] = $ ff;

Then, instead of just making a recursive call, you want to merge the new array into your current one with array_merge($return, listFolderFiles($dir.'/'.$ff)); 然后,您不仅要进行递归调用,还想通过array_merge($ return,listFolderFiles($ dir。'/'。$ ff));将新数组合并到当前数组中。

Finally, return at the end: return $return; 最后,在最后返回:return $ return;

Just merge them: 只需合并它们:

function listFolderFiles($dir) {
    $files = glob("$dir/*");
    foreach($files as $f) {
        if(is_dir($f)) {
            $files = array_merge($files, (array)listFolderFiles($f));
        }
    }
    return $files;
}

foreach(listFolderFiles('/path') as $file) {
    echo "<li>$file</li>";
}

Edited. 编辑。 Lots of ways but do it when you call the function maybe. 有很多方法,但是可能在您调用函数时执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM