Rumah >pembangunan bahagian belakang >tutorial php >PHP 递归实现层级树状展现数据

PHP 递归实现层级树状展现数据

巴扎黑
巴扎黑asal
2016-11-23 13:13:361469semak imbas

<?php
$db = mysql_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;root&#39;) or die(&#39;Can\&#39;t connect to database&#39;);
mysql_select_db(&#39;test&#39;) or die(&#39;Can\&#39;t find database : test&#39;);
$result = mysql_query(&#39;select id, fid, name from tree&#39;);
while($arr = mysql_fetch_array($result)){
    $data[] = array(
        &#39;id&#39; => $arr[&#39;id&#39;], 
        &#39;fid&#39; => $arr[&#39;fid&#39;],
        &#39;name&#39; => $arr[&#39;name&#39;], 
    );
}
// 将数据按照缩进简单排列 见图1
function data2arr($tree, $rootId = 0, $level = 0) {
    foreach($tree as $leaf) {
        if($leaf[&#39;fid&#39;] == $rootId) {
            echo str_repeat(&#39;    &#39;, $level) . $leaf[&#39;id&#39;] . &#39; &#39; . $leaf[&#39;name&#39;] . &#39;<br/>&#39;;
            foreach($tree as $l) {
                if($l[&#39;fid&#39;] == $leaf[&#39;id&#39;]) {
                    data2arr($tree, $leaf[&#39;id&#39;], $level + 1);
                    break;
                }
            }
        }
    }
}
data2arr($data);
echo &#39;<br/>-----------------------------------------------------------------------<br/>&#39;;
// 将数据按照所属关系封装 见图2
function arr2tree($tree, $rootId = 0) {
    $return = array();
    foreach($tree as $leaf) {
        if($leaf[&#39;fid&#39;] == $rootId) {
            foreach($tree as $subleaf) {
                if($subleaf[&#39;fid&#39;] == $leaf[&#39;id&#39;]) {
                    $leaf[&#39;children&#39;] = arr2tree($tree, $leaf[&#39;id&#39;]);
                    break;
                }
            }
            $return[] = $leaf;
        }
    }
    return $return;
}
$tree = arr2tree($data);
print_r($tree);
echo &#39;<br/>-----------------------------------------------------------------------<br/>&#39;;
// 将数据使用HTML再次展现 见图3
function tree2html($tree) {
    echo &#39;<ul>&#39;;
    foreach($tree as $leaf) {
        echo &#39;<li>&#39; .$leaf[&#39;name&#39;];
        if(! empty($leaf[&#39;children&#39;])) tree2html($leaf[&#39;children&#39;]);
        echo &#39;</li>&#39;;
    }
    echo &#39;</ul>&#39;;
}
tree2html($tree);

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:PHP 排列组合Artikel seterusnya:PHP之引用