2012-09-30 22 views
2

可能重複:
Displaying folders and making links of those folders使用RecursiveDirectoryIterator

我試圖使用RecursiveDirectoryIterator創建一個簡單的文件瀏覽器,但似乎無法推測出來...任何請幫助?

$cwd = '/path/to/somewhere'; 
if(isset($_GET['path']) && is_dir($cwd.$_GET['path'])) { 
    $cwd .= $_GET['path']; 
} 

$dir = new RecursiveDirectoryIterator($cwd); 
$iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST); 
while($iter->valid()) { 
    // skip unwanted directories 
    if(!$iter->isDot()) { 
     if($iter->isDir()) { 
      // output linked directory along with the number of files contained within 
      // for example: some_folder (13) 
     } else { 
      // output direct link to file 
     } 
    } 
    $iter->next(); 
} 

不知道這是最好的方法,但我的印象是RecursiveDirectoryIterator比均執行opendir()和水珠()方法快下我。

+1

你究竟想要弄清楚什麼? – Baba

回答

9

SELF_FIRSTCHILD_FIRST作爲無關RecursiveDirectoryIteratorRecursiveIteratorIterator

如果運行

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST); 

foreach ($iterator as $path) { 
    if ($path->isDir()) { 
     print($path->__toString() . PHP_EOL); 
    } else { 
     print($path->__toString() . PHP_EOL); 
    } 

你會得到

...\htdocs\lab\stockoverflow\css 
...\htdocs\lab\stockoverflow\css\a.css 
...\htdocs\lab\stockoverflow\css\b.css 
...\htdocs\lab\stockoverflow\css\c.css 
...\htdocs\lab\stockoverflow\css\css.php 
...\htdocs\lab\stockoverflow\css\css.run.php 

如果將其更改爲RecursiveIteratorIterator::CHILD_FIRST

...\htdocs\lab\stockoverflow\css\a.css 
...\htdocs\lab\stockoverflow\css\b.css 
...\htdocs\lab\stockoverflow\css\c.css 
...\htdocs\lab\stockoverflow\css\css.php 
...\htdocs\lab\stockoverflow\css\css.run.php 
...\htdocs\lab\stockoverflow\css 

你能看出差別在於當前文件夾的位置嗎

+0

@mister martin到底是什麼意思? – Baba

+0

「您能否看到差異在當前文件夾的位置」是指正在處理兒童之前或之後正在處理的'... \ htdocs \ lab \ stockoverflow \ css'文件夾。 – lmeurs

+0

你將如何擺脫點文件夾('.','..')?海報使用'$ path-> isDot()',但是這種方法不存在。我想你會手動檢查'!in_array($ path-> getBasename(),[「。」,「..」])'' – MDijkstra

相關問題