您好,登錄后才能下訂單哦!
小編給大家分享一下PHP如何實現(xiàn)無限極分類生成分類樹,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
現(xiàn)在的分類數(shù)據(jù)庫設(shè)計基本都是:每一個分類有一個id主鍵字段,一個pid指向父類的id,這樣便可實現(xiàn)無限級分類,取出的數(shù)據(jù)就是如下的格式:
$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]; //創(chuàng)建主鍵的數(shù)組引用 } 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]; //如果存在父級欄目,則添加進父級欄目的子欄目數(shù)組中 } } } return $tree; }
測試運行:
$cat = make_tree($arr); print_r($cat);
運行結(jié)果:
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] => 欄目十二 ) ) ) ) ) )
如果大家需要這樣的組裝格式,或者需要該格式方便后續(xù)的處理,可以嘗試此方法。
看完了這篇文章,相信你對“PHP如何實現(xiàn)無限極分類生成分類樹”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。