views:

53

answers:

2

Hi all,

I'm trying to use scandir to display a select list of folders listed in a specific directory (which works fine) however, I need it to also add the child folders (if there are any) into my select list. If anyone could help me, that would be great!

This is the structure I want:

<option>folder 1</option>
<option> --child 1</option>
<option> folder 2</option>
<option> folder 3</option>
<option> --child 1</option>
<option> --child 2</option>
<option> --child 3</option>

And this is the code I have (which only shows the parent folders) which I got from this thread (http://stackoverflow.com/questions/608450/using-scandir-to-find-folders-in-a-directory-php):

 $dir = $_SERVER['DOCUMENT_ROOT']."\\folder\\";

 $path = $dir;
 $results = scandir($path);

 $folders = array();
 foreach ($results as $result) {
    if ($result == '.' || $result == '..') continue;
    if (is_dir($path . '/' . $result)) {
      $folders[] = $result;
    };
 };

^^ but I need it to show the child directories also.. If anyone could help, that'd be great! :)

EDIT: Forgot to say that I don't want the files, only the folders..

+4  A: 
//Requires PHP 5.3
$it = new RecursiveTreeIterator(
    new RecursiveDirectoryIterator($dir));

foreach ($it as $k => $v) {
    echo "<option>".htmlspecialchars($v)."</option>\n";
}

You can customize the prefix with RecursiveTreeIterator::setPrefixPart.

Artefacto
+1  A: 
/* FUNCTION: showDir
 * DESCRIPTION: Creates a list options from all files, folders, and recursivly
 *     found files and subfolders. Echos all the options as they are retrieved
 * EXAMPLE: showDir(".") */
function showDir( $dir , $subdir = 0 ) {
    if ( !is_dir( $dir ) ) { return false; }

    $scan = scandir( $dir );

    foreach( $scan as $key => $val ) {
        if ( $val[0] == "." ) { continue; }

        if ( is_dir( $dir . "/" . $val ) ) {
            echo "<option>" . str_repeat( "--", $subdir ) . $val . "</option>\n";

            if ( $val[0] !="." ) {
                showDir( $dir . "/" . $val , $subdir + 1 );
            }
        }
    }

    return true;
}
abelito
thanks for this, but it's showing files aswell - I only want the folders themselves :)
SoulieBaby
Ahh, I fixed it for you :) If you need it to display the . and .., add the following lines after $scan = scandir:if ( $subdir == 0 ) { echo "<option>.</option><option>..</option>";}
abelito
thank you again, but now it's not showing up anything :(
SoulieBaby
wait figured it out, had to add in my $dir into is_dir($val) etc :D Thank you for your help! :)
SoulieBaby
lol, good. i just updated it with that exact same change. no problem, glad to help you get started! :)
abelito