您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)如何在PHP中利用遞歸實(shí)現(xiàn)一個(gè)層級(jí)樹(shù)狀展開(kāi)效果,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
實(shí)現(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ù)按照縮進(jìn)簡(jiǎn)單排列 見(jià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)系封裝 見(jià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) 見(jià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中利用遞歸實(shí)現(xiàn)一個(gè)層級(jí)樹(shù)狀展開(kāi)效果了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。