Reputation: 149
So, I literally spent two days trying to get this into my head. I want a function that creates a multidimensional array from a dirtree. I did it manually before and got this result:
Array ()
[cats] = Array()
[domestic] = Array ()
[wild] = Array ()
[dogs] = Array ()
[big] = Array ()
[small] = Array ()
[emptyfolder]
By manually I mean doing something like this within my function: $result['level1']['level2'] = array();
This doesn't work well because I don't know the depth of the dirtree beforehand.
The function also uses another function GetSubdirectories($directory)
which returns and array like this:
[0] = 'cats',
[1] = 'dogs'
[2] = 'emptyfolder'
So, here is the function in question:
<?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;
}
?>
From what I understand, the problem is "telling the function where to put the next arrays". I just don't get it and any help would be much appreciated!
SOLUTION
<?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);
}
?>
Upvotes: 3
Views: 295
Reputation: 53565
Just change:
$this->GetStructure(); // <-- how to I call the function?
to:
GetStructure($currentDirectory);
Upvotes: 0
Reputation: 9425
It sounds like you want to access the next element?
Don't use a foreach
, but a for
loop:
$keys = arraykeys($subdirectories);
$length = sizeof($keys);
for ($i = 0; $i < $length; $i++)
{
$structure[$node] = array();
$currentDirectory = $directory . "/" . $subdirectory;
$this->GetStructure($subdirectories[$i]);
}
however, if you mean set the result, then this may be it. I'm still confused:
$keys = arraykeys($subdirectories);
$length = sizeof($keys);
for ($i = 0; $i < $length; $i++)
{
$currentDirectory = $directory . "/" . $subdirectory;
$structure[$node] = $this->GetStructure($subdirectories[$i]);
}
Upvotes: 1