Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

scandir - PHP RecursiveDirectoryIterator

I want to do a RecursiveDirectoryIterator on a set of folders in a directory, say ./temp and then list the files in each folder according to the name of the folder.

For example I have the folders A and B.

In A, I have a list of files say, 1.txt, 2.php, 2.pdf, 3.doc, 3.pdf.

In B, I have 1.pdf, 1.jpg, 2.png.

I want my results to be like this:

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

How can this be done?

<?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 
    }} 
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a combination of RecursiveDirectoryIterator and RecursiveIteratorIterator to iterate through all subdirectories.

The snippet below will do what you require, although it is limited to only creating an array one array deep... this is to avoid getting into a recursive mess, within an already-confusing-to-procedural-brains small snippet.

$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;
            }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...