2009-11-27 59 views
0

我想使用遞歸掃描文件夾的函數,並將每次掃描的內容分配給一個數組。在PHP中以增量深度動態生成陣列

它足夠簡單,通過使用next()或foreach遞歸遍歷數組中的每個後續索引 - 但是如何動態地向數組添加深度層(無需將其硬編碼到函數中)會給我帶來問題。這裏有一些僞:

function myScanner($start){ 

    static $files = array(); 

    $files = scandir($start); 
    //do some filtering here to omit unwanted types 

    $next = next($files); 


    //recurse scan 

    //PROBLEM: how to increment position in array to store results 
    //$next_position = $files[][][].... ad infinitum 

    //myScanner($start.DIRECTORY_SEPARATOR.$next); 
} 

任何想法?

回答

2

嘗試這樣:

// $array is a pointer to your array 
// $start is a directory to start the scan 
function myScanner($start, &$array){ 
    // opening $start directory handle 
    $handle = opendir($start); 

    // now we try to read the directory contents 
    while (false !== ($file = readdir($handle))) { 
    // filtering . and .. "folders" 
    if ($file != "." && $file != "..") { 
     // a variable to test if this file is a directory 
     $dirtest = $start . DIRECTORY_SEPARATOR . $file; 

     // check it 
     if (is_dir($dirtest)) { 
     // if it is the directory then run the function again 
     // DIRECTORY_SEPARATOR here to not mix files and directories with the same name 
     myScanner($dirtest, $array[$file . DIRECTORY_SEPARATOR]); 
     } else { 
     // else we just add this file to an array 
     $array[$file] = ''; 
     } 
    } 
    } 

    // closing directory handle 
    closedir($handle); 
} 

// test it 
$mytree = array(); 
myScanner('/var/www', $mytree); 

print "<pre>"; 
print_r($mytree); 
print "</pre>"; 
+0

我會給它一個旋轉,雖然目前不工作... – sunwukung 2009-11-27 15:41:32

+0

再試一次,我修好了一點:) – silent 2009-11-27 15:42:14

+0

,完美的工作。我沒有考慮使用引用。此行: myScanner($ dirtest,$ array [$ file。DIRECTORY_SEPARATOR]); 是難倒我的人 - 我沒有看到聯想鍵在哪裏被添加 - 直到我明白參考啓動變量。我今天學到了一些有價值的東西 - 謝謝! – sunwukung 2009-11-27 18:54:20

0

嘗試使用此功能(和編輯你的需求):

function getDirTree($dir,$p=true) { 
    $d = dir($dir);$x=array(); 
    while (false !== ($r = $d->read())) { 
     if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) { 
      $x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false)); 
     } 
    } 

    foreach ($x as $key => $value) { 
     if (is_dir($dir.$key."/")) { 
      $x[$key] = getDirTree($dir.$key."/",$p); 
     } 
    } 

    ksort($x); 
    return $x; 
} 

它返回目錄的排序數組。

+1

許多感謝.... ......但沒有想冒犯 - 這是一個相當密集的功能,我想要的東西一點點溫和的 - 也許一些評論? – sunwukung 2009-11-27 15:33:32