PHP中遞歸的實現(附例子)

遞歸函數是一種調用本身的函數。寫遞歸函數時要當心,由於可能會無窮遞歸下去。必須確保有充分的方法來終止遞歸。php

一:使用參數引用完成遞歸函數。操做的是同一塊內存地址。函數

<?php
$i=1;
function test(&$i)
{
    echo $i;
    $i++;
    if ($i < 10){
        test($i);
    }
}
test($i);//輸出123456789
test($i);//輸出10

?>

 

二:使用全局變量完成遞歸函數。在函數域內部用 global 語句導入的一個真正的全局變量其實是創建了一個到全局變量的引用。例子中,test()函數內部的 $i 實際上只是程序第一行中($i = 1;)的變量 $i 的一個應用;url

<?php
$i = 1;
function test()
{
    global $i;
    echo $i;
    $i++;
    if ($i < 10){
        test();
    }
}
test();//輸出123456789
test();//輸出10

?>

 

三:使用靜態變量完成遞歸函數。static的做用:僅在第一次調用函數的時候對變量進行初始化,而且保留變量值。spa

<?php
function test()
{
    static $i = 1;
    echo $i;
  $i++;
    if ($i < 10) {
        test();
    }
    $i--;//在每一層遞歸結束時自減,這一句能夠幫助理解遞歸函數的執行過程
}
test();//輸出123456789
test();//輸出123456789
?>

 


例1. 使用全局變量的狀況遞歸遍歷文件夾下的全部文件 code

function getFiles($dir)
{
    global $arr; //引用全局變量
    if(is_dir($dir)){
        $handle = @opendir($dir);
        while($file=readdir($handle)){
            if(!in_array($file,array('.', '..'))){
                $dirr = $dir.'/'.$file;
                if(is_dir($dirr)){
                    getFiles($dirr); //遞歸讀子目錄
                }else{
                    array_push($arr, $dirr);
                }
            }
        }
    }
}
$arr = array(); //必須先定義全局變量
getFiles('E:/logs');
print_r($arr); 

 

例2:使用靜態變量的狀況遞歸遍歷文件夾下的全部文件blog

function getFiles ($dir)
{
    static $arr = array(); //使用靜態變量,防止每次遞歸都被覆蓋
    if(is_dir($dir)){
        $handle = opendir($dir);
        while($file=readdir($handle)){
            if(!in_array($file,array('.','..'))){
                $dirr = $dir."/".$file;
                if(is_dir($dirr)){
                    getFiles ($dirr);
                }else{
                    array_push($arr,$dirr);
                }      
            }
        }
    }
    return $arr;
}
$rows= array();
$rows = getFiles ('E:/logs');
print_r($rows);

 

例3:使用 glob() 函數或者 scandir() 函數的狀況遞歸遍歷文件夾下的全部文件遞歸

function getFiles($dir)
{
    static $arr = array(); //使用靜態變量,防止每次遞歸都被覆蓋
    if(is_dir($dir)){
        $handle = glob("$dir/*");
        //或者使用scandir() 函數,該函數的做用與 glob() 函數相同
      //$handle = scandir($dir); 
        foreach($handle as $filename){
            if(is_dir($filename)){
                getFiles($filename);
            }else{
                array_push($arr,$filename);
            }
        }
    }
    return $arr;
}
$rows= array();
$rows = getFiles ('E:/logs');
print_r($rows);   

 固然使用glob()函數,還能夠定義自獲取某類文件,好比只獲取 txt文件:glob("$dir/*.txt");進程

 

例4:利用遞歸來執行輪詢操做內存

//輪詢3次,進程須要駐守內存
function
getCheck($check='要處理的參數',$times = 1) { if(!$check){ return 'param error'; } $url = "https://www.xxxx.com/test.php"; $re = file_get_contents($url); if($re == 'error'){ $time = time(); echo date('Y-m-d H:i:s',$time).':'.$re.$times."<br>"; $times ++; if($times<4){ sleep(1); return getCheck($check,$times); }else{ return 'time out'; } }else{ return 'success'; } }
相關文章
相關標籤/搜索