程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP 遞歸生成樹狀行實例代碼

PHP 遞歸生成樹狀行實例代碼

編輯:關於PHP編程

本文介紹 PHP 遞歸生成樹狀行實例代碼

  1. <?php
  2.    header("content-type: text/html; charset=utf-8");
  3.    $connect = mysql_connect(localhost, root, 123456);
  4.    mysql_select_db("wz");
  5.    mysql_query("set names utf8");
  6.     //獲得頂節點
  7.    $sql = "select id, name,ischild from tree where parent = 0 order by id asc";
  8.    $result = mysql_query($sql);
  9.    while($row = mysql_fetch_array($result))
  10.    {
  11.       extract($row);
  12.          //如果有子節點,就在前面加個事件,以便展開或者關閉子節點
  13.       $icon = $ischild ? "<a href=javascript.:expand("div$id");> </a>":"-";
  14.       $name = $icon . $name;
  15.       echo "<div id=div" . $id . ">" . $name;
  16.       if($ischild)
  17.        {
  18.                   //遞歸獲取節點
  19.            getNode($id, 0);
  20.       }
  21.       echo "</div>";
  22.    }
  23.    function getNode($id, $level)
  24.    {
  25.       $sql = "select id, name, ischild from tree where parent = $id order by id asc ";
  26.        $result = mysql_query($sql);
  27.       $level ;
  28.      while($row = mysql_fetch_array($result))
  29.     {
  30.          extract($row);
  31.            $icon = $ischild ? "<a href=javascript.:expand("div$id");> </a>":"-";
  32.           $name = $icon . $name;  
  33.           echo "<div id=div" . $id . ">" . echoChar("    ", $level)  . $name;
  34.          if($ischild)
  35.            {
  36.              getNode($id, $level);
  37.           }
  38.           echo "</div>";
  39.      }
  40.    }
  41.    
  42.   function echoChar($char, $num)
  43.   {
  44.        for($i=0;$i< $num; $i )
  45.       {
  46.           $strChar .= $char;
  47.       }
  48.       return $strChar;
  49.    }
  50.    ?>
  51.    <script language="javascript">
  52.        function expand(id)
  53.       {
  54.            var obj = document.getElementById(id).childNodes;
  55.            for(var i=0;i<obj.length;i )
  56.            {
  57.               if(obj[i].nodeName == "DIV")
  58.                {
  59.                    switch(obj[i].style.display)
  60.                   {
  61.                        case "":
  62.                        case "block":
  63.                         obj[i].style.display = "none";
  64.                         break;
  65.                       case "none":
  66.                         obj[i].style.display = "block";
  67.                         break;
  68.                    }
  69.                }
  70.            }
  71.        }
  72.    </script>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved