本文實例講述了php無限極分類實現(xiàn)方法。分享給大家供大家參考,具體如下:
今天給大家?guī)淼氖莗hp的無限極分類技術(shù),本人把無限極分類劃分為兩種。
首先我把數(shù)據(jù)庫表給大家看看,數(shù)據(jù)庫是tasks,數(shù)據(jù)庫表也是tasks
第一種方法(數(shù)組法)
這種方法其實是先把所有的數(shù)據(jù)查詢出來,重點在于生成的二維數(shù)組
?php //分類方法 function make_list($parent,$deep = 0){ global $tasks;//申明全局變量 global $strArr;//申明全局變量 $qianzhui = str_repeat("nbsp;",$deep)."|--"; foreach ($parent as $key => $value) { $strArr[] = $qianzhui.$value; if(isset($tasks[$key])){ make_list($tasks[$key],++$deep);//遞歸調(diào)用函數(shù) } } } //數(shù)據(jù)庫連接 $dbc = mysqli_connect("localhost","root","1234","tasks"); //拼接sql語句 $q = "select task_id,parent_id,task from tasks where date_completed = '0000-00-00:00:00:00' order by parent_id,date_added asc"; //執(zhí)行sql $r = mysqli_query($dbc,$q); //遍歷結(jié)果集 while (list($task_id,$parent_id,$task) = mysqli_fetch_array($r,MYSQLI_NUM)) { //組成數(shù)組(一級鍵為parent_id,二級鍵為task_id,值為任務(wù)內(nèi)容) $tasks[$parent_id][$task_id] = $task; } //打印數(shù)組 echo "pre>"; print_r($tasks); echo "/pre>"; make_list($tasks[0]); echo "pre>"; //打印縮進數(shù)組 print_r($strArr); echo "/pre>"; ?>
運行結(jié)果圖
第二種方法(查表法)
這種方法其實是在一開始只查詢出parent_id=0的所有任務(wù),然后采用遞歸的方式,動態(tài)生成查詢條件,然后把每條記錄的task_id又作為task_id,這樣又進行新一輪的查詢,知道查詢結(jié)果為空。
?php function findArr($where = "parent_id = 0",$deep = 0){ $dbc = mysqli_connect("localhost","root","1234","tasks"); global $strArr; $q = "select task_id,parent_id,task from tasks where ".$where." order by parent_id,date_added asc"; $r = mysqli_query($dbc,$q); $qianzhui = str_repeat("nbsp;", $deep)."|--"; while (list($task_id,$parent_id,$task) = mysqli_fetch_array($r,MYSQLI_NUM)) { $strArr[] = $qianzhui.$task; //拼接查詢條件 $where = "parent_id = ".$task_id; //遞歸查詢 findArr($where,++$deep); } } findArr(); //打印縮進數(shù)組 echo "pre>"; print_r($strArr); echo "/pre>"; ?>
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學運算技巧總結(jié)》
希望本文所述對大家PHP程序設(shè)計有所幫助。