Malcolm
October 7th, 2004, 23:39
I wrote a function that recursively grabs a directory tree.
Here my directory structure:
/
/directory
/directory/sub-dir
/directory/sub-dir/sub-sub-dir
/new1
/new2
/new2/new3
/new2/new4
/new2/new5
/new2/new5/new6
This is my code:
/*function: list_tree()
VARS:
$dir = start path
$level = how deep the dir is in the tree (recursive entry only)
*/
function list_tree($dir, $level=0)
{
// Define Arrays
$rec = array();
$dirs = array();
if (is_dir($dir)){
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if(!preg_match("#\.#", $file) && is_dir($dir . "/" . $file) && !is_file($dir . "/" . $file) && !is_link($dir . "/" . $file)){
$dirs[] = $dir . "/" . $file."&".$level;
$rec = list_tree($dir . "/" . $file, $level+1);
}//end:if
for($x = 0; $x < sizeof($rec); $x++){
$dirs[] = $rec[$x];
}//end:for
}//end:while
closedir($dh);
}//end:if
}//end:if
return $dirs;
}//end:functions
With this code I should see
directory&1
sub-dir&2
sub-sub-dir&3
new1&1
new2&1
new3&2
new4&4
new5&4
new6&5
But what i get is
directory&1
and
sub-dir&2
sub-sub-dir&3
sub-sub-dir&3
sub-sub-dir&3
repeated 7 times, then the other right stuff.
Any idea whats going on?
To view a live example jump to http://www.thenwing.com/testing
Malcolm
October 8th, 2004, 18:49
Get an answer, just had to replace my for loop with a array_merge.
Incase anyone wants the full code for their own use:
function list_tree($dir, $level=0)
{
// Define Arrays
$rec = array();
$dirs = array();
if (is_dir($dir)){
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (is_dir($dir . '/' . $file)
&& !is_link($dir . '/' . $file)
&& ($file != '.')
&& ($file != '..')) {
$dirs[] = $dir . "/" . $file."&".$level;
$rec = list_tree($dir . "/" . $file, $level+1);
$dirs = array_merge($dirs, $rec);
}//end:if
}//end:while
closedir($dh);
}//end:if
}//end:if
return $dirs;
}//end:functions
Martin
October 8th, 2004, 19:14
Oh yeah, was just about to give you the solutions. :P
Malcolm
October 8th, 2004, 20:10
Oh yeah, was just about to give you the solutions. :P
Thanks anyways Marty-pants :P
vBulletin v3.6.2, Copyright ©2000-2010, Jelsoft Enterprises Ltd.