2009-12-14 156 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(),这是一个内置的功能,似乎做几乎你所追求的。请注意,它列出了所有文件夹中的条目 - 包括文件,文件夹,...