Good day to you,
Here i'm still working on my list of files pushed to an array.

I'm now working on recursively display the list, when it read the files and it find a directory, it should go through and list the files and folders.. so on..

I know my code is wrong, this is why I come to you, I want to learn.

My code do the thing but only does it once.

My problem : My code don't read recursively, it only go to the 2nd level of foler if any.

How could I improve this ?


<?php

$directory = "Art/";
function dirList ($directory)
{

//create 2 arrays - one for folders and one for files
   $folders = array();
   $files = array();

// create a handler for the directory
$handler = opendir($directory);

// keep going until all files in directory have been read
while (false !== ($file = readdir($handler))) {  

    // if $file isn't this directory or its parent,
    // add it to the results array
    if ($file != '.' && $file != '..')

    // If file is directory, mark it in bold.
   if(is_dir($directory.$file)) { 
    array_push($folders,$file);

    // Else not styled
    }else{
    array_push($files,$file);

}
}


// tidy up: close the handler
closedir($handler);

foreach($folders as $folder) {
  echo "<strong>".$folder."</strong><br />";

echo "<div>";
dirList($directory."$folder.");

echo "</div><br/><br/>";


}

foreach($files as $file) {
  echo $file."<br />";
}


}

dirList($directory);

?> 

The big picture is a menu of files and folder.
Each folder result should be placed in a div.
If there is a folder create a new div within the other and list the files in....

Thanks !

    To do it, just call the function again from within the function. That's essentially the basics of recursion.

    So where you check to see if it's a directory, instead of just pushing into the array, push the result of the the next call into the current result.

    Here's a simple example:

    <?php
    
    function dirList($path)
    {
    	// Fix the $path (remove trailing '/');
    	if(substr($path, -1) == '/')
    	{
    		$path = substr($path, 0, -1);
    	}
    
    // Get a listing of everything in the current directory
    $files = glob($path.'/*');
    
    $list = array();
    foreach($files as $file)
    {
    	// Remove the path from the filename...
    	$file = str_replace($path.'/', '', $file);
    	if(is_dir($path.'/'.$file))
    	{
    		$list[$path][$file] = dirList($path.'/'.$file);
    	}
    	else
    	{
    		$list[$path][] = $file;
    	}
    }
    
    return $list;
    }
    
    $listing = dirList('./Art');
    
    echo '<pre>'.print_r($listing, 1).'</pre>';

    You can then iterate over this array in the form of:

    foreach($listing as $dir=>$item) {
        if(is_array($item))
        {
            // Iterate again over $item looking for more dirs
        }
        else
        {
            // This item is a file in the directory $dir
        }
    }
      Write a Reply...