当前位置:Gxlcms > PHP教程 > php写的无限级selectTree类

php写的无限级selectTree类

时间:2021-07-01 10:21:17 帮助过:14人阅读

  1. /*

  2. author: nick
  3. 功能:生成SeletTree
  4. 属性:
  5. $result 结果集
  6. $id_field 自身id字段
  7. $parent_field 父类id字段
  8. $option_text 选项显示名称
  9. $select_name 下拉菜单的名称
  10. $elected 默认选中
  11. $no_top 是否需要顶层选项
  12. $level 层深度
  13. $parent_id 同层中的id
  14. */
  15. class SelectTree{
  16. public $result;
  17. public $select_name;
  18. public $option_text;
  19. public $elected;
  20. public $id_field;
  21. public $parent_field;
  22. public $no_top;
  23. public $level;
  24. public $parent_id;
  25. public $getarray;
  26. function __construct($result,$id_field,$parent_field,$option_text,$select_name='',$elected=0,$no_top=0,$level=0,$parent_id=0){
  27. $this->result =$result;
  28. $this->id_field =$id_field;
  29. $this->parent_field =$parent_field;
  30. $this->option_text =$option_text;
  31. $this->select_name =$select_name;
  32. $this->elected =$elected;
  33. $this->no_top =$no_top;
  34. $this->level =$level;
  35. $this->parent_id =$parent_id;
  36. $this->getarray =self::getArray();
  37. }

  38. /*

  39. 功能:返回Tree二维数组
  40. */
  41. function getArray(){
  42. $arrays=array();
  43. while($row=mysql_fetch_array($this->result)){
  44. $arrays[$row[$this->parent_field]][$row[$this->id_field]]=$row;
  45. }
  46. return $arrays;
  47. }

  48. /*

  49. 功能:获取SelectTree
  50. */
  51. function getSelectTree(){
  52. $tree = '';
  53. return $tree;
  54. }

  55. /*

  56. 功能:递归构建树状结构
  57. */
  58. function buildTree($array,&$tree,$option_value,$option_text,$selected,$level=0,$parent_id=0){
  59. if(is_array($array[$parent_id])){
  60. for($i=0;$i<$level;$i++)
  61. $space .= ' '; //选项缩进深度
  62. foreach($array[$parent_id] as $key => $value){
  63. if($value[$option_value] == $selected){
  64. $tree .= '";
  65. }else{
  66. $tree .= '";
  67. }
  68. $tree .=self::buildTree($array,&$tree,$option_value,$option_text,$selected,$level+1,$key);
  69. }
  70. }else{
  71. $tree .= '';
  72. }
  73. }
  74. }

  75. /*----------*/

  76. header("CONTENT-TYPE:TEXT/HTML;CHARSET=UTF-8");
  77. mysql_connect("localhost","root","root");
  78. mysql_select_db("tree");
  79. mysql_query('set names utf8');
  80. $result = mysql_query("select * from tvmenu");
  81. $tree=new SelectTree($result,'id','bid','name','tree');
  82. echo $tree->getSelectTree();
  83. ?>

人气教程排行