Home  >  Article  >  php教程  >  php递归用法与递归目录实例

php递归用法与递归目录实例

WBOY
WBOYOriginal
2016-06-08 17:23:171309browse

在php中递归算法是我们比得不多的一种数据遍历方式了,下面我来给大家介绍一下利用递归来做一下用的东西吧。

<script>ec(2);</script>

看一个简单的递归实例

例1

 代码如下 复制代码

function demo($a) { 

    static $sum=1; 

    if($a > 1){ 

        $sum*=$a; 

        demo(--$a); 

    }else{ 

        $a=$sum; 

        } 

        return $sum; 


 

echo demo(10);

例2

遍历目录

 代码如下 复制代码

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();
?>

输出结果:


    Directory:jquery
  • jquery-1.3.2.js

  • jquery-1.3.2.min.js

  • jquery-1.3.2-vsdoc2.js

  • test.html

  • common.js


    • Directory:jquery/d
    • common.js

    • jquery-1.3.2.js


Statement:
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