欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php写的无限级selectTree类

程序员文章站 2024-01-05 11:02:34
...
  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$space .= ' '; //选项缩进深度
  61. foreach($array[$parent_id] as $key => $value){
  62. if($value[$option_value] == $selected){
  63. $tree .= '";
  64. }else{
  65. $tree .= '";
  66. }
  67. $tree .=self::buildTree($array,&$tree,$option_value,$option_text,$selected,$level+1,$key);
  68. }
  69. }else{
  70. $tree .= '';
  71. }
  72. }
  73. }
  74. /*----------*/

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