我想对目录中的一组文件夹执行RecursiveDirectoryIterator,说./temp,然后根据该文件夹的名称列出每个文件夹中的文件。

例如,我有AB文件夹。

在A中,我有一个文件列表,例如1.txt2.php2.pdf3.doc3.pdf

在B中,我有1.pdf1.jpg2.png

我希望我的结果是这样的:

A => List of files in A
B => List of files in B

如何才能做到这一点?
<?php
$scan_it = new RecursiveDirectoryIterator("./temp");
foreach(new RecursiveIteratorIterator($scan_it) as $file =>$key) {
    $filetypes = array("pdf");
    $filetype = pathinfo($file, PATHINFO_EXTENSION);
    if (in_array(strtolower($filetype), $filetypes)) {
        $dlist=basename($file); //sort
?>
<ul>
    <li>
        <?php echo substr(dirname($file),11);?>
    </li>
    <li>
        <a href="<?php echo $file;?>"><?php echo basename($file);?></a>
    </li>
</ul>
<?php
    }}
?>

最佳答案

结合使用 RecursiveDirectoryIterator RecursiveIteratorIterator 遍历所有子目录。

下面的代码片段将满足您的要求,尽管它仅限于仅创建一个深度为一个数组的数组...这是为了避免在一个已经令人困惑的过程脑小代码片段中陷入递归困惑的局面。

$array = array();

foreach ($iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator("./temp",
        RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST) as $item) {
    // Note SELF_FIRST, so array keys are in place before values are pushed.

        $subPath = $iterator->getSubPathName();
            if($item->isDir()) {
                // Create a new array key of the current directory name.
                $array[$subPath] = array();
            }
            else {
                // Add a new element to the array of the current file name.
                $array[$subPath][] = $subPath;
            }
    }
}

关于php - PHP RecursiveDirectoryIterator,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20045622/

10-11 22:44
查看更多