在 PHP 開發中,遞歸是一種常見且強大的資料遍歷方式。簡單來說,遞歸就是函數在其定義中直接或間接呼叫自身的過程。這種技巧特別適合處理樹狀結構資料,如檔案目錄、分類選單等。本文將透過兩個實際範例,帶您深入理解 PHP 遞歸的應用。
首先看一個經典的遞歸範例——計算階乘。以下程式碼展示如何使用靜態變數配合遞歸來計算 10 的階乘:
<?php
function demo($a) {
static $sum = 1;
if ($a > 1) {
$sum *= $a;
demo(--$a);
} else {
$a = $sum;
}
return $sum;
}
echo demo(10); // 輸出 3628800
?>
此範例利用 static 關鍵字保持變數狀態,透過遞歸呼叫逐步累乘,最終返回結果。雖然迴圈也能完成,但遞歸寫法更符合數學定義的直觀邏輯。
實際開發中,遞歸最常見的用途是遍歷目錄樹。下方類別 listdir 完整展示了如何遞歸掃描資料夾並輸出巢狀列表:
<?php
class listdir {
var $depth;
var $dirname;
var $list;
var $tostring;
function __construct($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;
}
// 將結果格式化為 HTML 列表字串
function tostring($dir = "") {
if ($dir == "") $dir = $this->dirname;
$d = @dir($dir);
$this->tostring .= "<UL>\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 .= "<LI>" . $item . "</LI>\n";
}
}
}
$this->depth -= 1;
$d->close();
$this->tostring .= "</UL>\n";
return $this->tostring;
}
}
$wapdir = "jquery";
$d = new listdir($wapdir);
echo $d->tostring();
?>
執行上述程式碼將產生類似以下的 HTML 結構:
<UL>
Directory:jquery
<LI>jquery-1.3.2.js</LI>
<LI>jquery-1.3.2.min.js</LI>
<LI>jquery-1.3.2-vsdoc2.js</LI>
<LI>test.html</LI>
<LI>common.js</LI>
<UL>
Directory:jquery/d
<LI>common.js</LI>
<LI>jquery-1.3.2.js</LI>
</UL>
</UL>
@dir() 抑制警告,實際專案建議加入完善的錯誤檢查機制。遞歸是處理階層式資料的利器,掌握其核心邏輯——「自我呼叫 + 終止條件」——能讓您輕鬆解決目錄遍歷、選單生成、樹狀資料處理等常見問題。實務上建議搭配快取機制優化效能,避免重複掃描造成資源浪費。