這篇文章主要為大家詳細介紹了PHP遞迴實現層級樹狀展開的相關資料,需要的朋友可以參考下
:
實現代碼:
<?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'], ); } // 將資料按照縮排簡單排列 見圖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/>'; // 將資料按照所屬關係封裝 見圖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/>'; // 將資料使用HTML再次展現 見圖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);
總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。