《PHP應(yīng)用:PHP遞歸實(shí)現(xiàn)層級(jí)樹狀展開》要點(diǎn):
本文介紹了PHP應(yīng)用:PHP遞歸實(shí)現(xiàn)層級(jí)樹狀展開,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
PHP應(yīng)用本文實(shí)例為大家分享了PHP遞歸實(shí)現(xiàn)層級(jí)樹狀展開的主要代碼,供大家參考,具體內(nèi)容如下
PHP應(yīng)用效果圖:
PHP應(yīng)用
PHP應(yīng)用實(shí)現(xiàn)代碼:
PHP應(yīng)用
<?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ù)依照縮進(jìn)簡單排列 見圖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);
PHP應(yīng)用以上就是本文的全部內(nèi)容,希望對(duì)大家學(xué)習(xí)php程序設(shè)計(jì)有所幫助.
維易PHP培訓(xùn)學(xué)院每天發(fā)布《PHP應(yīng)用:PHP遞歸實(shí)現(xiàn)層級(jí)樹狀展開》等實(shí)戰(zhàn)技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培養(yǎng)人才。
轉(zhuǎn)載請(qǐng)注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/6989.html