1

PHP関数から複数の値を返したいのですが、次のコードとして機能しませんでした。

この関数は、特定のフォルダーとその再帰フォルダー内のファイル名を検索し、ファイル名を配列に格納するために使用されます。

この例では、特定の(メイン)フォルダーは次のように呼び出されます。F:\ test
再帰フォルダーは次のように呼び出されます:F:\ test \ subfolder

メインフォルダとサブフォルダには7つのファイルがあり、ファイル名の形式は次のとおりです。

メインフォルダの場合:1.txt、2.txt、3.txt、4.txt
サブフォルダの場合:5.txt、6.txt、7.txt

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

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

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

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

        } else {
            if ($level>0) //in a recursive folder
            {
                $dir_matched[$j]=$file;
                $j++;
            }
            else //in main folder
            {
            $files_matched[$i] = $file;
            $i++;
            }               
        }    
}
closedir( $dh );
//print_r ($files_matched);
//print_r ($dir_matched);   I tested this before return, both works fine.

return array($files_matched,$dir_matched);
}



echo "<pre>";
list($a,$b) = getDirectory("F:\test");
print_r ($a);   // this will result the same as array $files_matched, it ok!
print_r ($b);   // but i don't know why I cannot get the array of $dir_matched??
echo "</pre>";   

ご覧のとおり、配列が1つしか取得できないほど奇妙ですか?$dir_matched配列の内容を取得できるアイデアはありますか?

4

1 に答える 1

0

現在の記述方法では、再帰呼び出しから値をキャプチャしていません。関数内で、次の行に:

getDirectory( "$path/$file", ($level+1) );

そこから戻り値を取得する必要があります。何かのようなもの:

$files_matched[++$i] = getDirectory( "$path/$file", ($level+1));

$iここで必要なものではない場合があります。ここでも、の場合と同じようにインクリメントする必要がありますelse statement。または、サブディレクトリを反映するために別の変数にキャプチャする必要があります。これは、実行する内容によって異なります。

于 2012-10-27T20:33:23.810 に答える