
文章插圖
這篇文章主要為大家詳細介紹了PHP遞歸實現(xiàn)層級樹狀展開的相關(guān)資料,需要的朋友可以參考下
效果圖:
實現(xiàn)代碼:
<?php
$db = mysql_connect(‘localhost’, ‘root’, ‘root’) or die(‘Can’t connect to database’);
mysql_select_db(‘test’) or die(‘Can’t find database : test’);
$result = mysql_query(‘select id, fid, name from tree’);
while($arr = mysql_fetch_array($result)){
$data[] = array(
‘id’ => $arr[‘id’],
‘fid’ => $arr[‘fid’],
‘name’ => $arr[‘name’],
);
}
// 將數(shù)據(jù)按照縮進簡單排列 見圖1
function data2arr($tree, $rootId = 0, $level = 0) {
foreach($tree as $leaf) {
if($leaf[‘fid’] == $rootId) {
echo str_repeat(‘ ‘, $level) . $leaf[‘id’] . ‘ ‘ . $leaf[‘name’] . ‘<br/>’;
foreach($tree as $l) {
if($l[‘fid’] == $leaf[‘id’]) {
data2arr($tree, $leaf[‘id’], $level + 1);
break;
}
}
}
}
}
data2arr($data);
echo ‘<br/>———————————————————————–<br/>’;
// 將數(shù)據(jù)按照所屬關(guān)系封裝 見圖2
function arr2tree($tree, $rootId = 0) {
$return = array();
foreach($tree as $leaf) {
if($leaf[‘fid’] == $rootId) {
foreach($tree as $subleaf) {
if($subleaf[‘fid’] == $leaf[‘id’]) {
$leaf[‘children’] = arr2tree($tree, $leaf[‘id’]);
break;
}
}
$return[] = $leaf;
}
}
return $return;
}
$tree = arr2tree($data);
print_r($tree);
echo ‘<br/>———————————————————————–<br/>’;
// 將數(shù)據(jù)使用HTML再次展現(xiàn) 見圖3
function tree2html($tree) {
echo ‘<ul>’;
foreach($tree as $leaf) {
echo ‘<li>’ .$leaf[‘name’];
if(! emptyempty($leaf[‘children’])) tree2html($leaf[‘children’]);
echo ‘</li>’;
}
echo ‘</ul>’;
}
tree2html($tree);
總結(jié):以上就是本篇文的全部內(nèi)容,希望能對大家的學(xué)習(xí)有所幫助 。
相關(guān)推薦:
php實現(xiàn)通過文件頭判斷格式的方法
php時間函數(shù)的用法及實例分析
PHP引用返回用法實例詳解
以上就是PHP遞歸實現(xiàn)層級樹狀展開的方法的詳細內(nèi)容,更多請關(guān)注其它相關(guān)文章!
以上關(guān)于本文的內(nèi)容,僅作參考!溫馨提示:如遇健康、疾病相關(guān)的問題,請您及時就醫(yī)或請專業(yè)人士給予相關(guān)指導(dǎo)!
「愛刨根生活網(wǎng)」www.malaban59.cn小編還為您精選了以下內(nèi)容,希望對您有所幫助:- php學(xué)生管理系統(tǒng)源碼免費 php商品管理系統(tǒng)代碼
- bim怎么算 bim的算法介紹
- Api 國內(nèi)PHP開源接口框架 api管理系統(tǒng)php源碼
- 選擇排序算法c語言代碼 c語言選擇排序法詳情
- c語言取子串函數(shù)講解 php字符串拼接函數(shù)
- 一個完整的網(wǎng)上商城的源碼 php商城系統(tǒng)技術(shù)難點
- php編程試題及答案 php手冊菜鳥教程
- 教你刪除數(shù)組最后一位 php刪除數(shù)組最后一個元素使用什么方法
- 詳解pos共識算法的特點 pos算法原理
- 截至2021年9月 白楊SEO:新百度算法更新大全49條
