所以,我真的花了两天时间试图把这个放到我的脑海里。我想要一个从脏树创建多维数组的函数。我之前手动完成并得到了这个结果:
Array ()
[cats] = Array()
[domestic] = Array ()
[wild] = Array ()
[dogs] = Array ()
[big] = Array ()
[small] = Array ()
[emptyfolder]
通过手动,我的意思是在我的函数中做这样的事情:$result['level1']['level2'] = array();
这效果不好,因为我事先不知道污垢的深度。
该函数还使用另一个函数GetSubdirectories($directory)
返回和数组,如下所示:
[0] = 'cats',
[1] = 'dogs'
[2] = 'emptyfolder'
所以,这里是有问题的功能:
<?php
public function GetStructure($directory, $node = 'content') //the root folder is content
{
if (!isset($structure))
{
$structure = array();
}
$subdirectories = $this->GetSubdirectories($directory);
if (is_array($subdirectories))
{
foreach ($subdirectories as $subdirectory)
{
//add new subarray
$structure[$node] = array();
//set the current path
$currentDirectory = $directory . "/" . $subdirectory;
//repeat
$this->GetStructure(); // <-- how to I call the function?
}
}
return $structure;
}
?>
据我了解,问题是“告诉函数将下一个数组放在哪里”。我只是不明白,任何帮助将不胜感激!
解决方案
<?php
public function PopulateArrayWithDirtree($dir, &$array = false)
{
$subDirs = $this->GetSubdirectories($dir);
if (is_array($subDirs))
{
for ($i = 0; $i < sizeof($subDirs); $i++)
{
$array[$subDirs[$i]] = array();
$this->PopulateArrayWithDirtree(($dir . "/" . $subDirs[$i]), $array[$subDirs[$i]]); //repeat
}
}
return true;
}
public function Test()
{
$path = $this->contentpath;
$structure = array();
$this->PopulateArrayWithDirtree($path, $structure);
print_r($structure);
}
?>