[原创] Tips: 两种目录遍历的方法


目录的遍历是个老问题,主要用在目录遍历类操作,比如删除、统计磁盘占用等等情况。目录就是一个典型的树形结构,递归是最简单的方法了。

function ErgodicDirectory1( $dir ){
$dp = opendir ( $dir );
while ( $file = readdir ( $dp )){
if ( $file != ' . ' && $file != ' .. ' ){
$path = $dir . " / " . $file ;
if ( is_dir ( $path )){
echo " 目录: " . $path . chr ( 10 );
ErgodicDirectory1(
$path );
}
else {
echo " 文件: " . $path . chr ( 10 );
}
}
}
closedir ( $dp );
}

利用一个栈来递归消除:

function ErgodicDirectory2( $dir ){
$stack = array ( $dir );
while ( ! empty ( $stack )){
$curr_dir = array_pop ( $stack );
if ( $dp = opendir ( $curr_dir )){
while (( $file = readdir ( $dp ))){
if ( $file != ' . ' && $file != ' .. ' ){
$curr_file = " $curr_dir/$file " ;
if ( is_dir ( $curr_file )){
echo " 目录: " . $curr_file . chr ( 10 );
$stack [] = $curr_file ;
}
else {
echo " 文件: " . $curr_file . chr ( 10 );
}
}
}
closedir ( $dp );
}
}
}

你可能感兴趣的:(tips)