Home > php教程 > php手册 > php递归遍历目录实现程序

php递归遍历目录实现程序

WBOY
Release: 2016-05-25 16:55:40
Original
1163 people have browsed it
PHP本身自带的有一个readdir的函数,不过只能读取当前的目录,根据这个函数,我写了另外一个函数,用来实现我的需求。函数的原理很简单,主要就是用了一下递归调用。
 代码如下 复制代码

class listdir{
var $depth;
var $dirname;
var $list;
var $tostring;

function listdir($dir){
$this->dirname=$dir;
$this->depth=0;
$this->tostring=”";
}

//把结果保存进多维数组
function getlist($dir=”"){
if($dir==”")$dir=$this->dirname;
$d=@dir($dir);
while(false!==($item=$d->read()))
{
if($item!=”.”&&$item!=”..”)
{
$path=$dir.”/”.$item;
if(is_dir($path)){
$this->depth+=1;
$this->getlist($path);
}else{
$this->list[$this->depth][]=$item;
}
}
}
$this->list[$this->depth]['directory']=$dir;
$this->depth-=1;
$d->close();
return $this->list;
}

//字符窜化结果

function tostring($dir=”"){
if($dir==”")$dir=$this->dirname;
$d=@dir($dir);
$this->tostring.=”

    n”;
    $this->tostring.=”Directory:”.$dir.”n”;
    while(false!==($item=$d->read()))
    {
    if($item!=”.”&&$item!=”..”)
    {
    $path=$dir.”/”.$item;
    if(is_dir($path)){
    $this->depth+=1;
    $this->tostring($path);
    }else{
    $this->tostring.=”
  • ”.$item.”
  • n”;
    }
    }
    }
    $this->depth-=1;
    $d->close();
    $this->tostring.=”
n”;
return $this->tostring;
}
}
$wapdir=”jquery”;
$d=new listdir($wapdir);
echo $d->tostring();
?>

递归创建多级目录

1.先判断最底层目录div/css/layout是否存在;2.判断div/css/layout的上层目录div/css是否存在,不存在则以div/css作为参数递归进行


下面是程序代码:

 代码如下 复制代码

function mkdirs($dir)
{
if(!is_dir($dir))
{
if(!mkdirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0777)){
return false;
}
}
return true;
}
mkdirs('div/css/layout');


同样的思路,php用rmdir和unlink递归删除多级目录的代码:

function rmdirs($dir)
{
$d = dir($dir);
while (false !== ($child = $d->read())){
if($child != '.' && $child != '..'){
if(is_dir($dir.'/'.$child))
rmdirs($dir.'/'.$child);
else unlink($dir.'/'.$child);
}
}
$d->close();
rmdir($dir);
}



文章链接:

随便收藏,请保留本文地址!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template