這篇文章主要介紹了關於PHP中的無限級分類和無限嵌套評論,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
回顧
上一篇文章我們講到實戰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;
然後我們虛擬出一些資料出來,最後長這個樣子。
下面 我們直接看程式碼實作。
<?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的子目錄,然後使用開始遞歸呼叫。最後的輸出就是這個樣子的。
無限嵌套評論
先來看下這個 無限嵌套評論長什麼樣子。如圖:
上面的栗子,又是一個經典的可以使用遞迴解決的案例。還是來看下資料結構。
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中文網其他相關文章!

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

記事本++7.3.1
好用且免費的程式碼編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

禪工作室 13.0.1
強大的PHP整合開發環境