Apr
26

PHP遍历整个文件目录结构     2009

 09:42    377    0   jane 程序 代码 源码 不指定 | |
PHP遍历整个文件目录结构


define('DS', DIRECTORY_SEPARATOR);

function rec_list_files($from = '.')

{

    if(!is_dir($from)) {

        return array();

     }

    $files = array();

    if($dh = opendir($from))

     {

        while(false !== ($file = readdir($dh))) {

            

            if($file == '.' || $file == '..') {

                continue;

             }

            $path = $from . DS . $file;

            

            if (is_file($path)) {

                $files[] = $path;

             }

            $files = array_merge($files, rec_list_files($path));

         }

        closedir($dh);

     }

    return $files;

}


function deep_first_list_files($from = '.')

{

    if(!is_dir($from)) {

        return false;

     }

    $files = array();

    $dirs = array($from);



    while(NULL !== ($dir = array_pop($dirs))) {

  

        if( $dh = opendir($dir)) {

            while( false !== ($file = readdir($dh))) {

                if($file == '.' || $file == '..') {

                    continue;

                 }

                $path = $dir . DS . $file;

                if(is_dir($path)) {

                    $dirs[] = $path;

     //var_dump($dirs);

                 } else {

                    $files[] = $path;

                 }

             }

            closedir($dh);

         }

     }

    return $files;

}


function breadth_first_files($from = '.') {

    $queue = array(rtrim($from, DS).DS);// normalize all paths

    $files = array();

    while($base = array_shift($queue )) {

  //var_dump($queue);

        if (($handle = opendir($base))) {

            while (($child = readdir($handle)) !== false) {

               if( $child == '.' || $child == '..') {

                    continue;

                 }

                if (is_dir($base.$child)) {

                    $combined_path = $base.$child.DS;

                    array_push($queue, $combined_path);

                 } else {

                    $files[] = $base.$child;

                 }

             }

            closedir($handle);

         } // else unable to open directory => NEXT CHILD

     }

    return $files; // end of tree, file not found

}


分别使用递归、广度优先(BFS 堆栈)、深度优先(DFS 队列) 来实现

作者:jane@SEO
地址:http://www.laohucheng.com/post/353/
版权所有©转载时必须以链接形式注明作者和原始出处及本声明!

Tags: 引用(0)
发表评论
昵称 [注册]
密码 游客无需密码
网址
电邮
打开HTML 打开UBB 打开表情 隐藏 记住我