2009-10-06 69 views
2

我正在爲我的公司編寫一個簡單的網絡報告系統。我爲index.php編寫了一個腳本,它獲取「reports」目錄中的文件列表,並自動創建一個指向該報告的鏈接。它工作正常,但我的問題在於,readdir()不斷返回。除目錄的內容外還有..目錄指針。有沒有什麼辦法來防止這種OTHER THAN循環返回的數組並手工剝離它們?PHP readdir()返回「。」和「..」條目

下面是好奇的相關代碼:

//Open the "reports" directory 
$reportDir = opendir('reports'); 

//Loop through each file 
while (false !== ($report = readdir($reportDir))) 
{ 
    //Convert the filename to a proper title format 
    $reportTitle = str_replace(array('_', '.php'), array(' ', ''), $report); 
    $reportTitle = strtolower($reportTitle); 
    $reportTitle = ucwords($reportTitle); 

    //Output link 
    echo "<a href=\"viewreport.php?" . $report . "\">$reportTitle</a><br />"; 
} 

//Close the directory 
closedir($reportDir); 

回答

14

在你上面的代碼,你可以在while環追加作爲一線:

if ($report == '.' or $report == '..') continue; 
+0

一個很簡單的解決方案。我希望readdir上有一些參數選項可以避免這種情況,但我猜不是。這個問題有幾乎同時的答案,幾乎相同的確切解決方案。接受這個,因爲它是第一個。 – DWilliams 2009-10-06 14:22:36

+0

非常乾淨的示例+1 – Andrew 2009-10-06 14:41:50

4
array_diff(scandir($reportDir), array('.', '..')) 

甚至更​​好:

foreach(glob($dir.'*.php') as $file) { 
    # do your thing 
} 
1

我不知道另一種方式,如「。」和「..」也是適當的目錄。由於您正在循環以形成正確的報告網址,因此您可能只需輸入if即可忽略...以供進一步處理。

編輯
Paul Lammertsma比我快一點。這是你想要的解決方案;-)

2

不,這些文件屬於一個目錄,因此readdir應該返回它們。我會考慮所有其他行爲被打破。

總之,只要跳過它們:

while (false !== ($report = readdir($reportDir))) 
{ 
    if (($report == ".") || ($report == "..")) 
    { 
    continue; 
    } 
    ... 
}