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 に答える