PHP在多个目录中输出多个文件

时间:2016-01-19 03:28:53

标签: php arrays foreach glob scandir

我有一个名为PDFS的主目录,有5个子目录代表年份(2011年,2012年,2013年,2014年,2015年)。在每个"年目录"是11 pdf。我需要访问PDFS目录并获取所有"年目录",然后在每个"年目录中获取所有pdf"在页面上显示。例如,2011年"年目录中的pdf"将列在2011年标题下。与2012年,2013年相同。我尝试过很多不同的事情。我可以输出"年份目录"使用scandir()。我可以在单个"年目录中输出文件"使用foreach循环和glob()。我不能为我的生活弄清楚如何输出每个目录" s"除了在每个" year目录"上使用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 />";
    }

1 个答案:

答案 0 :(得分:0)

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

//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)。