簡體   English   中英

PHP在多個目錄中輸出多個文件

[英]PHP Output Multiple Files In Multiple Directories

我有一個名為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 />";
    }

您處在正確的軌道上,這段代碼應該可以解決問題:

//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時無需計算變量i

  • 如果您將字符串手動設置在一起,則嘗試逐步生成它,然后將生成的字符串與手動的字符串進行比較,直到適合為止。 (您用點將兩個字符串連接起來.

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM