我有一个列出目录中文件夹的数组。到目前为止,我一直在对文件夹名称进行硬编码,但是我认为我可以轻松地创建脚本来解析目录,并将每个文件夹名称分配给数组。这样一来,我可以轻松地添加文件夹,而不必再次触摸脚本...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)),
但很明显,这并不正常工作,因为它不是喂养阵列正确我只是得到一个字符串在我的选项列表中...我确定这是一个简单的转换步骤,我很想...
@Scott,我有一个更短的方法,但它取决于有一个设置的最大深度。你的树木结构会增长到什么深度,或者3或4级的树木会如此深? – 2009-12-15 00:22:06
嗨道格,它只会是一个深度。 – 2009-12-15 01:30:34