What's new

PHP directory recursion weirdness

Malcolm

Not a Moderator
I wrote a function that recursively grabs a directory tree.

Here my directory structure:
Code:
/
/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:
PHP:
/*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
Code:
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
Code:
directory&1
and
Code:
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
 
OP
Malcolm

Malcolm

Not a Moderator
Get an answer, just had to replace my for loop with a array_merge.
Incase anyone wants the full code for their own use:
http://www.phpbuilder.com/board/showthread.php?s=&postid=10560394#post10560369 said:
PHP:
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
 

Top