2009-12-14 162 views
0

我有一個列出目錄中文件夾的數組。到目前爲止,我一直在對文件夾名稱進行硬編碼,但是我認爲我可以輕鬆地創建腳本來解析目錄,並將每個文件夾名稱分配給數組。這樣一來,我可以輕鬆地添加文件夾,而不必再次觸摸腳本...PHP動態填充數組

主題陣列創建一個選項列表下拉菜單中列出的每個文件夾...

目前,該陣列是硬編碼像這樣...

「選項」=>陣列( 「夾一個」=> 「文件夾1」, 「文件夾中兩個」=> 「文件夾2」)),

但我要把它基於動態在給定目錄中找到的任何文件夾上。

下面是我用來解析目錄並將文件夾名返回到數組的腳本。它工作正常。

function getDirectory($path = '.', $level = 0) 
{ 
// Directories to ignore when listing output. 
$ignore = array('.', '..'); 

// Open the directory to the handle $dh 
$dh = @opendir($path); 

// Loop through the directory 
while(false !== ($file = readdir($dh))) 
    { 
    // Check that this file is not to be ignored 
    if(!in_array($file, $ignore)) 
     { 
     // Show directories only 
     if(is_dir("$path/$file")) 
      { 
      // Re-call this same function but on a new directory. 
      // this is what makes function recursive. 
      //echo $file." => ".$file. ", "; 
      // need to return the folders in the form expected by the array. Probably could just add the items directly to the array? 
      $mydir2=$mydir2.'"'.$file.'" => "'.$file. '", '; 
      getDirectory("$path/$file", ($level+1)); 
     } 
    } 
} 
return $mydir2; 
// Close the directory handle 
closedir($dh); 
} 

而且這裏是我先來獲取這些文件夾入陣...

$mydir = getDirectory('/images/'); 
"options" => array($mydir)), 

但很明顯,這並不正常工作,因爲它不是餵養陣列正確我只是得到一個字符串在我的選項列表中...我確定這是一個簡單的轉換步驟,我很想...

+0

@Scott,我有一個更短的方法,但它取決於有一個設置的最大深度。你的樹木結構會增長到什麼深度,或者3或4級的樹木會如此深? – 2009-12-15 00:22:06

+0

嗨道格,它只會是一個深度。 – 2009-12-15 01:30:34

回答

0

你想創建一個數組,而不是字符串。

// Replace 
$mydir2=$mydir2.'"'.$file.'" => "'.$file. '", '; 

// With 
$mydir2[$file] = $file; 

另外,在返回之前關閉$dh。現在,closedir永遠不會被調用。

+0

感謝Mikael,正是我在找的! – 2009-12-15 01:37:53

1

Why not just look at php.net?它有遞歸目錄列表中的幾個例子。

下面是一個例子:

<?php 
public static function getTreeFolders($sRootPath = UPLOAD_PATH_PROJECT, $iDepth = 0) { 
     $iDepth++; 
     $aDirs = array(); 
     $oDir = dir($sRootPath); 
     while(($sDir = $oDir->read()) !== false) { 
     if($sDir != '.' && $sDir != '..' && is_dir($sRootPath.$sDir)) { 
      $aDirs[$iDepth]['sName'][] = $sDir; 
      $aDirs[$iDepth]['aSub'][] = self::getTreeFolders($sRootPath.$sDir.'/',$iDepth); 
     } 
     } 
     $oDir->close(); 
     return empty($aDirs) ? false : $aDirs; 
} 
?> 
+0

謝謝Steven,我對目錄列表很滿意。我的問題的關鍵是如何讓我的函數創建到數組中的文件夾。 – 2009-12-15 01:31:43

0

這是一個簡單的函數,它將返回一個可用目錄數組,但它不是遞歸的,因爲它的深度有限。我喜歡它,因爲它是如此簡單:

<?php 
    function get_dirs($path = '.'){ 
    return glob( 
     '{' . 
     $path . '/*,' . # Current Dir 
     $path . '/*/*,' . # One Level Down 
     $path . '/*/*/*' . # Two Levels Down, etc. 
     '}', GLOB_BRACE + GLOB_ONLYDIR); 
    } 
?> 

您可以使用它像這樣:

$dirs = get_dirs(WP_CONTENT_DIR . 'themes/clickbump_wp2/images'); 
0

如果你使用PHP5 +你可能會喜歡scandir(),這是一個內置的功能,似乎做幾乎你所追求的。請注意,它列出了所有文件夾中的條目 - 包括文件,文件夾,...