ディレクトリ・ツリー
ディレクトリの中身をずらっとツリー構造で取得したいときがあります。
例では、起点となるディレクトリのパスを引数に持つ、最低限の関数です。サイトマップの生成などにどうぞ。
1. function dir_tree_recursion( $path ){ 2. if( !is_dir($path)) return false; 3. $nodes = array(); 4. if( $h = opendir($path)){ 5. while(( $node = readdir($h)) !== false ){ 6. if(( $node !== '.' ) && ( $node !== '..' )) continue; 7. if( is_dir( $path .'/'. $node )){ 8. array_push( $nodes, dir_tree_recursion( $path .'/'. $node )); 9. }elseif( is_file( $path .'/'. $node )){ 10. array_push( $nodes, $path .'/'. $node ): 11. } 12. } 13. closedir($h); 14. } 15. return $nodes; 16. }
2行目:
引数で渡されたパスがディレクトリであれば処理を続行します。
3行目:
戻り値となる配列を用意。
4〜14行:
パスのディレクトリ・ハンドルを開き、ディレクトリからノードを取得し、ノードに対する処理を行っていきます。
6行目:
ノードが自身と上位階層のディレクトリを指す場合は除外します。
7〜8行:
パスとノードを結合(※1)した対象がディレクトリである場合、再帰的に処理を続行した結果を戻り値に追加します。
9〜10行:
対象がファイルの場合、ノードを戻り値に追加します。
13行目:
ディレクトリ・ハンドルを閉じます。
15行目:
戻り値を返します。
PHPを覚えるなら
新品価格 |