PHP RecursiveDirectoryIterator [英] PHP RecursiveDirectoryIterator

查看:66
本文介绍了PHP RecursiveDirectoryIterator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对目录中的一组文件夹(例如./temp)执行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.

例如,我有文件夹AB.

For example I have the folders A and B.

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

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

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

我希望我的结果像这样:

I want my results to be like this:

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 
    }} 
?>

推荐答案

//Managed to put this together and it somehow works for me. If you have other options please provide. Thanks

$path='./temp';
$dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);

    foreach ($files as $file=>$mykey) {
        if(is_dir($file)) {

$directory = $file;
$mydir = new RecursiveIteratorIterator(new RecursiveRegexIterator(new RecursiveDirectoryIterator($directory,RecursiveDirectoryIterator::FOLLOW_SYMLINKS), 
// match both pdf file extensions and directories
                '#(?<!/)\.pdf$|^[^\.]*$#i'),true);
    foreach ($mydir as $myfile=>$mykey) {
    $result[] = $myfile.'<br />';

    $filetypes = array("pdf");
    $filetype = pathinfo($myfile, PATHINFO_EXTENSION);
    if (in_array(strtolower($filetype), $filetypes)) {


// output all matches substr(dirname($file),11)

?>


    <div><h3<?php echo count($result);?>>
    <span><?php echo  substr(PHP_EOL . $directory . PHP_EOL . PHP_EOL,13);?></span></h3></div>

    <?php if (!empty($mydir)) {
    foreach ($mydir as $d) {
    if (strpos($d->getFilename(), '.pdf') !== FALSE) {?>
    <div><ul><li><a href="<?php echo $d;?>"><?php echo basename($d->getPath() . DIRECTORY_SEPARATOR . $d->getFilename() . PHP_EOL);?></a></li></ul></div>
        <?php }
         }

            }
        }
}


        }



}

这篇关于PHP RecursiveDirectoryIterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆