所以,我花了两天的时间试图把它放到我脑海里。我想要一个从dirtree创建多维数组的函数。我之前手动完成了这个结果:
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);
}
?>
答案 0 :(得分:1)
听起来你想要访问下一个元素?
请勿使用foreach
,而应使用for
循环:
$keys = arraykeys($subdirectories);
$length = sizeof($keys);
for ($i = 0; $i < $length; $i++)
{
$structure[$node] = array();
$currentDirectory = $directory . "/" . $subdirectory;
$this->GetStructure($subdirectories[$i]);
}
但是,如果你的意思是设置结果,那么可能就是这样。我还是很困惑:
$keys = arraykeys($subdirectories);
$length = sizeof($keys);
for ($i = 0; $i < $length; $i++)
{
$currentDirectory = $directory . "/" . $subdirectory;
$structure[$node] = $this->GetStructure($subdirectories[$i]);
}
答案 1 :(得分:0)
只需改变:
$this->GetStructure(); // <-- how to I call the function?
为:
GetStructure($currentDirectory);