【发布时间】: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