3

所以,我真的花了两天时间试图把这个放到我的脑海里。我想要一个从脏树创建多维数组的函数。我之前手动完成并得到了这个结果:

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);
    }
?>
4

2 回答 2

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]);
}
于 2012-08-16T19:39:57.887 回答
0

只是改变:

$this->GetStructure(); // <-- how to I call the function?

至:

GetStructure($currentDirectory);
于 2012-08-16T21:21:18.123 回答