首页 > 后端开发 > php教程 > 按照前台输出格式来写一个函数遍历文件夹下的文件和子文件夹

按照前台输出格式来写一个函数遍历文件夹下的文件和子文件夹

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
发布: 2016-06-06 20:18:32
原创
1123 人浏览过

<code>function my_scandir($file){
    if($f = opendir($file)){

        while($r = readdir($f)){
            if($r != '..' && $r != '.'){
                $c = $file.'/'.$r;
                if(is_dir($c)){
                    echo $r.'<br>';
                    my_scandir($c);
                }else{
                    echo $r.'<br>';
                }
            }
        }
    }
}


my_scandir('clone2');</code>
登录后复制
登录后复制

前台输出为
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
如何修改代码?

回复内容:

<code>function my_scandir($file){
    if($f = opendir($file)){

        while($r = readdir($f)){
            if($r != '..' && $r != '.'){
                $c = $file.'/'.$r;
                if(is_dir($c)){
                    echo $r.'<br>';
                    my_scandir($c);
                }else{
                    echo $r.'<br>';
                }
            }
        }
    }
}


my_scandir('clone2');</code>
登录后复制
登录后复制

前台输出为
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再调用。

普通写法:

<code>function read_dir_content($parent_dir, $depth = 0){
    $str_result = "";

    $str_result .= "<li>". dirname($parent_dir) ."</li>";
    $str_result .= "<ul>";
    if ($handle = opendir($parent_dir)) 
    {
        while (false !== ($file = readdir($handle)))
        {
            if(in_array($file, array('.', '..'))) continue;
            if( is_dir($parent_dir . "/" . $file) ){
                $str_result .= "<li>" . read_dir_content($parent_dir . "/" . $file, $depth++) . "</li>";
            }
            $str_result .= "<li>{$file}</li>";
        }
        closedir($handle);
    }
    $str_result .= "</ul>";


    return $str_result;
}


echo "<ul>" . read_dir_content("/folder") . "</ul>";
</code>
登录后复制

如果你的php > 5.31:

<code>function iterateDirectory($i)
{
    echo '<ul>';
    foreach ($i as $path) {
        if ($path->isDir())
        {
            echo '<li>';
            iterateDirectory($path);
            echo '</li>';
        }
        else
        {
            echo '<li>'.$path.'</li>';
        }
    }
    echo '</ul>';
}

$dir = '/folder';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

iterateDirectory($iterator);</code>
登录后复制
相关标签:
php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
怎么学好php
来自于 1970-01-01 08:00:00
0
0
0
PHP扩展intl
来自于 1970-01-01 08:00:00
0
0
0
php数据获取?
来自于 1970-01-01 08:00:00
0
0
0
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板