2015-02-11 33 views
1

我使用此代碼,以便從目錄中獲取列表文件:PHP - 刪除'。'並且從目錄中的文件獲取值「..」

$dir = '/restosnapp_cms/images/'; 
if ($dp = opendir($_SERVER['DOCUMENT_ROOT'] . $dir)) { 
    $files = array(); 
    while (($file = readdir($dp)) !== false) { 
     if (!is_dir($dir . $file)) { 
      $files[] = $file; 
     } 
    } 
    closedir($dp); 
} else { 
    exit('Directory not opened.'); 
} 

我想擺脫的價值觀「」和'..'。

Screenshot

是否有可能做到這一點?謝謝。 :)

+2

使用if條件 – frunkad 2015-02-11 20:02:29

+1

當然,您可以在輸出之前對其進行過濾。有許多陣列功能可以幫助這種或那種方式。或者你可以在循環中放一個'if',只輸出不是'.'或'..'的名字。 – GolezTrol 2015-02-11 20:03:43

+2

難道這不容易嗎? '$ files = array_filter(glob(「$ dir/*」),'is_file');' – AbraCadaver 2015-02-11 20:20:51

回答

6

只是檢查他們先:

while ($file = readdir($p)) { 
    if ($file == '.' || $file == '..') { 
     continue; 
    } 
    // rest of your code 
} 
+0

就像一個魅力!謝謝:) – serendipochi 2015-02-11 20:07:26

+1

+1 - 我曾經有過一些情況,我後來想添加更多不應該列出的文件名,在這種情況下,一個'in_array($ file,array('。','..',。 ..))'有時更容易。 – Keelan 2015-02-11 20:07:36

1

DirectoryIterator比更有趣* DIR功能:

$dir = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] . $dir); 
foreach($dir as $file) { 
    if (!$file->isDir() && !$file->isDot()) { 
     $files[] = $file->getPathname(); 
    } 
} 

但底線是,無論你做哪種方式,你需要使用條件。