【问题标题】:PHP Output Multiple Files In Multiple DirectoriesPHP在多个目录中输出多个文件
【发布时间】:2016-01-19 03:28:53
【问题描述】:

我有一个名为 PDFS 的主目录,其中有 5 个子目录代表年份(2011、2012、2013、2014、2015)。在每个“年目录”中有 11 个 pdf。我需要访问 PDFS 目录并获取所有“年份目录”,然后获取每个“年份目录”中的所有 pdf 以显示在页面上。因此,例如 2011 年“年目录”中的 pdf 将列在 2011 年标题下。与 2012 年、2013 年等相同。我尝试了很多不同的东西。我可以使用 scandir() 输出“年份目录”。我可以使用 foreach 循环和 glob() 将文件输出到单个“年份目录”中。除了在每个“年份目录”上使用 glob() 执行多个 foreach 循环之外,我一生都无法弄清楚如何输出每个“年份目录”的文件。必须有一种更动态的方式来设置它。有什么建议么?我觉得我需要在 foreach 中使用某种 foreach?这是我正在使用的:

//set main directory
$dir = 'PDFS';

//gets sub directories of PDFS directory
$directories = scandir($dir);

//removes the first to indexes in the directories array that are just dots
unset($directories[0]);
unset($directories[1]);

//outputs an array of the sub directories from scandir() starting at index 2
print_r($directories);

//initialize $i variable for loop
$i=0;

//if I manually set the $dir variable to "PDFS/2011/*" this will output links
//to each pdf inside the 2011 year directory
    foreach(glob($dir) as $file) {
        $i++;
        echo "<a href='$file'>$file</a><br />";
    }

【问题讨论】:

    标签: php arrays foreach glob scandir


    【解决方案1】:

    你在正确的轨道上,这段代码应该可以解决问题:

    //set main directory
    $mainDir = 'PDFS';
    
    //gets sub directories of PDFS directory
    $subDirectories = scandir($mainDir);
    
    //removes the first two indexes in the directories array that are just dots
    unset($subDirectories[0]);
    unset($subDirectories[1]);
    
    // first loop through all sub directories ...
    foreach($subDirectories as $subDirectory) {
        echo '<h1>'.$subDirectory.'</h1>';
        // ... and then loop through all files in each sub directory
        foreach(glob($mainDir.'/'.$subDirectory.'/*') as $file) {
            echo "<a href='$file'>$file</a><br />";
        }
    }
    

    我更改了一些 var 名称以便更好地理解。

    一些事情:

    • 当您使用 foreach 时,不需要计数 var i

    • 如果您手动将一个字符串设置在一起,然后尝试逐步生成它,并将生成的字符串与手动生成的字符串进行比较,直到合适为止。 (你用一个点.连接两个字符串)

    • 您可以配置 glob 函数,使其仅查找某些文件类型 (*.pdf)。

    【讨论】:

    • 天哪,我不是很亲近吗?哈!非常感谢您的帮助,最后一件事。 2015 年输出的最后一个循环首先列出第 10 个月和第 11 个月。比如:PDFS/2015/10-2015.pdf、PDFS/2015/11-2015.pdf、PDFS/2015/2-2015.pdf、PDFS/2015/3-2015.pdf等...我可以排序理解为什么,但所有其余的都以正确的顺序输出。我可以做些什么来重新排序最后一次通过?
    • 不客气。关于顺序:在“完美世界”中,它们应该/将被命名为 01-2015.pdf、02-2015.pdf 等,那么顺序应该是正确的。否则,您可以手动影响顺序,例如在这种情况下检查第二个循环中有关文件名长度或模式的每个字符串。哦,顺便说一句:如果您的问题已通过答案解决,您应该考虑将适当的答案标记为“已解决”。 ;)
    • 哦,对了,抱歉,这是我关于堆栈溢出的第一篇文章。我将在前面用零重命名它们。无论哪种方式,链接都需要在我输出它们时重命名为几个月......如果我无法弄清楚,我将保存它以用于新帖子。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多