0

我有一个函数在特定路径中获取递归文件夹的文件名:

function getDirectory( $path = '.', $level = 0 ){

$ignore = array( 'cgi-bin', '.', '..');
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.

$dh = @opendir( $path );
// Open the directory to the handle $dh
$files_matched = array(); 


while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory

    if( !in_array($file, $ignore ) && !preg_match("/^.*\.(rar|txt)$/", $file) ){
    // Check that this file is not to be ignored

        if( is_dir( "$path/$file" ) ){
        // Its a directory, so we need to keep reading down...

            echo "<strong>$spaces $file</strong><br />";

            getDirectory( "$path/$file", ($level+1) );
            // Re-call this same function but on a new directory.
            // this is what makes function recursive.

        } else {
            $files_matched[$i] = $file;
            $i++;
        }

    }

}

closedir( $dh );
// Close the directory handle
return $files_matched;
}

echo "<pre>";
$files = getDirectory("F:\Test");
foreach($files as $file) printf("%s<br />", $file);
echo "</pre>";

我使用 $files_matched 将文件名存储在数组中。

对于上述结果,它只显示“F:\test”下的文件名。

实际上,我在“F:\test”下有一个子文件夹。如何使用数组显示这些文件名进行存储?

如果我修改了代码:

$files_matched[$i] = $file;
$i++;

进入:

echo "$files<br />";

这会很好,我只是不知道为什么使用数组来存储文件名以供以后处理是行不通的?

感谢帮助。

4

1 回答 1

0

我不记得我从哪里得到这个代码,但它有效。

<?php

function getDirectoryTree( $outerDir , $x){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d)  ){
            $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d , $x);
        }else{
            if (($x)?ereg($x.'$',$d):1)
            $dir_array[ $d ] = $d;
        }
    }
    return $dir_array;
}

var_dump( getDirectoryTree(getcwd(),'') );
于 2012-10-23T18:05:56.350 回答