PHP中的無限級分類、無限巢狀評論

蕭瀟發表於2019-03-03

回顧

上一篇文章我們講到實戰PHP資料結構基礎之遞迴。來回顧下什麼是遞迴?

一般來說,遞迴被稱為函式自身的呼叫。

遞迴在開發中的實際運用

N級分類

無限級的分類在平常的開發中是常見的需求,並且在不少面試題中都會碰到。不管你做什麼專案,應該都碰到過類似的問題。下面,我們就使用遞迴的思想,實戰一把。

  • SQL結構
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;
複製程式碼

然後我們虛擬出一些資料出來,最後長這個樣子。

clipboard.png

下面 我們直接看程式碼實現。

<?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的子目錄,然後使用開始遞迴呼叫。最後的輸出是這個樣子的。

clipboard.png

無限巢狀評論

先來看下這個 無限巢狀評論長什麼樣子。如圖:

clipboard.png

上面的栗子,又是一個經典的可以使用遞迴解決的案例。還是來看下資料結構。

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基礎資料結構專題系列目錄地址:github.com/... 主要使用PHP語法總結基礎的資料結構和演算法。還有我們日常PHP開發中容易忽略的基礎知識和現代PHP開發中關於規範、部署、優化的一些實戰性建議,同時還有對Javascript語言特點的深入研究。

相關文章