這篇文章主要介紹了PHP實現無限極分類生成分類樹的方法,結合實例形式簡單分析了無限極分類的原理與實現方法,涉及PHP數組遍歷與判斷相關操作技巧,需要的朋友可以參考下
本文實例講述了PHP實現無限極分類生成分類樹的方法。分享給大家供大家參考,具體如下:
現在的分類資料庫設計基本上都是:每一個分類有一個id主鍵字段,一個pid指向父類的id,這樣便可實現無限級分類,取出的資料就是如下的格式:
$arr = array( array("id" => 1 , "pid" => 0 , 'cat' => '栏目一'), array("id" => 2 , "pid" => 0 , 'cat' => '栏目二'), array("id" => 3 , "pid" => 1 , 'cat' => '栏目三'), array("id" => 4 , "pid" => 2 , 'cat' => '栏目四'), array("id" => 5 , "pid" => 1 , 'cat' => '栏目五'), array("id" => 6 , "pid" => 5 , 'cat' => '栏目六'), array("id" => 7 , "pid" => 5 , 'cat' => '栏目七'), array("id" => 8 , "pid" => 6 , 'cat' => '栏目八'), array("id" => 9 , "pid" => 1 , 'cat' => '栏目九'), array("id" => 10 , "pid" => 0 , 'cat' => '栏目十'), array("id" => 11 , "pid" => 10 , 'cat' => '栏目十一'), array("id" => 12 , "pid" => 11 , 'cat' => '栏目十二'), array("id" => 13 , "pid" => 2 , 'cat' => '栏目十三'), array("id" => 14, "pid" => 13 , 'cat' => '栏目十四') );
不多說,直接上處理程式碼:
//生成无限极分类树 function make_tree($arr){ $refer = array(); $tree = array(); foreach($arr as $k => $v){ $refer[$v['id']] = & $arr[$k]; //创建主键的数组引用 } foreach($arr as $k => $v){ $pid = $v['pid']; //获取当前分类的父级id if($pid == 0){ $tree[] = & $arr[$k]; //顶级栏目 }else{ if(isset($refer[$pid])){ $refer[$pid]['subcat'][] = & $arr[$k]; //如果存在父级栏目,则添加进父级栏目的子栏目数组中 } } } return $tree; }
測試運行:
$cat = make_tree($arr); print_r($cat);
執行結果:
Array ( [0] => Array ( [id] => 1 [pid] => 0 [cat] => 栏目一 [subcat] => Array ( [0] => Array ( [id] => 3 [pid] => 1 [cat] => 栏目三 ) [1] => Array ( [id] => 5 [pid] => 1 [cat] => 栏目五 [subcat] => Array ( [0] => Array ( [id] => 6 [pid] => 5 [cat] => 栏目六 [subcat] => Array ( [0] => Array ( [id] => 8 [pid] => 6 [cat] => 栏目八 ) ) ) [1] => Array ( [id] => 7 [pid] => 5 [cat] => 栏目七 ) ) ) [2] => Array ( [id] => 9 [pid] => 1 [cat] => 栏目九 ) ) ) [1] => Array ( [id] => 2 [pid] => 0 [cat] => 栏目二 [subcat] => Array ( [0] => Array ( [id] => 4 [pid] => 2 [cat] => 栏目四 ) [1] => Array ( [id] => 13 [pid] => 2 [cat] => 栏目十三 [subcat] => Array ( [0] => Array ( [id] => 14 [pid] => 13 [cat] => 栏目十四 ) ) ) ) ) [2] => Array ( [id] => 10 [pid] => 0 [cat] => 栏目十 [subcat] => Array ( [0] => Array ( [id] => 11 [pid] => 10 [cat] => 栏目十一 [subcat] => Array ( [0] => Array ( [id] => 12 [pid] => 11 [cat] => 栏目十二 ) ) ) ) ) )
以上是php無限極分類生成分類樹的實作方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!