function my_scandir($file){ if($f = opendir($file)){ while($r = readdir($f)){ if($r != '..' && $r != '.'){ $c = $file.'/'.$r; if(is_dir($c)){ echo $r.'
'; my_scandir($c); }else{ echo $r.'
'; } } } }}my_scandir('clone2');
前台輸出為
public
admin.php
css
admin.css
style.css
view.php
sys
class.admin.php
我想要這樣的效果
public
-admin.php
-css
--admin.css
--style.css
view.php
sys
-class.admin.php
如何修改代碼?
回複內容:
function my_scandir($file){ if($f = opendir($file)){ while($r = readdir($f)){ if($r != '..' && $r != '.'){ $c = $file.'/'.$r; if(is_dir($c)){ echo $r.'
'; my_scandir($c); }else{ echo $r.'
'; } } } }}my_scandir('clone2');
前台輸出為
public
admin.php
css
admin.css
style.css
view.php
sys
class.admin.php
我想要這樣的效果
public
-admin.php
-css
--admin.css
--style.css
view.php
sys
-class.admin.php
如何修改代碼?
增加一個參數$depth,預設值0。
檔案名稱之前輸出$depth個減號。
然後每次遞迴時就把$depth加1再調用。
普通寫法:
function read_dir_content($parent_dir, $depth = 0){ $str_result = ""; $str_result .= "". dirname($parent_dir) .""; $str_result .= "
"; if ($handle = opendir($parent_dir)) { while (false !== ($file = readdir($handle))) { if(in_array($file, array('.', '..'))) continue; if( is_dir($parent_dir . "/" . $file) ){ $str_result .= "
- " . read_dir_content($parent_dir . "/" . $file, $depth++) . "
"; } $str_result .= "
- {$file}
"; } closedir($handle); } $str_result .= "
"; return $str_result;}echo "
" . read_dir_content("/folder") . "
";
如果你的php > 5.31:
function iterateDirectory($i){ echo '
'; foreach ($i as $path) { if ($path->isDir()) { echo '
- '; iterateDirectory($path); echo '
'; } else { echo '
- '.$path.'
'; } } echo '
';}$dir = '/folder';$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));iterateDirectory($iterator);