上一篇文章咱們講到實戰PHP數據結構基礎之遞歸。來回顧下什麼是遞歸?php
通常來講,遞歸被稱爲函數自身的調用。mysql
無限級的分類在日常的開發中是常見的需求,而且在很多面試題中都會碰到。無論你作什麼項目,應該都碰到過相似的問題。下面,咱們就使用遞歸的思想,實戰一把。git
CREATE TABLE `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `categoryName` varchar(100) NOT NULL, `parentCategory` int(11) DEFAULT '0', `sortInd` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
而後咱們虛擬出一些數據出來,最後長這個樣子。github
下面 咱們直接看代碼實現。面試
<?php $dsn = "mysql:host=127.0.0.1;port=3306;dbname=light-tips;charset=UTF8;"; $username = 'root'; $password = 'admin'; $pdo = new PDO($dsn, $username, $password); $sql = 'SELECT * FROM `categories` ORDER BY `parentCategory`, `sortInd`'; $result = $pdo->query($sql, PDO::FETCH_OBJ); $categories = []; foreach ($result as $category) { $categories[$category->parentCategory][] = $category; } function showCategoryTree($categories, $n) { if (isset($categories[$n])) { foreach ($categories[$n] as $category) { echo str_repeat('-', $n) . $category->categoryName . PHP_EOL; showCategoryTree($categories, $category->id); } } return; } showCategoryTree($categories, 0);
能夠看到,咱們首先獲取到了全部的數據,而後按照父級ID歸類。這是一個很是棒的數據結構。想象一下,咱們把展現頂級目錄下全部子目錄的問題分解成了展現本身的類目標題和展現數據中parentCategory爲當前目錄id的子目錄,而後使用開始遞歸調用。最後的輸出是這個樣子的。算法
先來看下這個 無限嵌套評論長什麼樣子。如圖:sql
上面的栗子,又是一個經典的可使用遞歸解決的案例。仍是來看下數據結構。segmentfault
CREATE TABLE `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `comment` varchar(500) NOT NULL, `username` varchar(50) NOT NULL, `datetime` datetime NOT NULL, `parentID` int(11) NOT NULL, `postID` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
你們能夠本身實踐一遍,先不要看下面的內容。數據結構
<?php $dsn = "mysql:host=127.0.0.1;port=3306;dbname=light-tips;charset=UTF8;"; $username = 'root'; $password = 'admin'; $pdo = new PDO($dsn, $username, $password); $sql = 'SELECT * FROM `comments` WHERE `postID` = :id ORDER BY `parentId`, `datetime`'; $stmt = $pdo->prepare($sql); $stmt->setFetchMode(PDO::FETCH_OBJ); $stmt->execute([':id' => 1]); $result = $stmt->fetchAll(); $comments = []; foreach ($result as $comment) { $comments[$comment->parentID][] = $comment; } function showComments(array $comments, $n) { if (isset($comments[$n])) { foreach ($comments[$n] as $comment) { echo str_repeat('-', $n) . $comment->comment . PHP_EOL; showComments($comments, $comment->id); } } return; } showComments($comments, 0);
使用遞歸進行目錄文件的掃描的栗子。數據結構和算法
<?php function showFiles(string $dir, array &$allFiles) { $files = scandir($dir); foreach ($files as $key => $value) { $path = realpath($dir . DIRECTORY_SEPARATOR . $value); if (!is_dir($path)) { $allFiles[] = $path; } else if ($value != "." && $value != "..") { showFiles($path, $allFiles); $allFiles[] = $path; } } return; } $files = []; showFiles('.', $files); foreach ($files as $file) { echo $file . PHP_EOL; }
PHP基礎數據結構專題系列目錄地址:地址 主要使用PHP語法總結基礎的數據結構和算法。還有咱們平常PHP開發中容易忽略的基礎知識和現代PHP開發中關於規範、部署、優化的一些實戰性建議,同時還有對Javascript語言特色的深刻研究。