首頁 >後端開發 >php教程 >php寫的無限級selectTree類

php寫的無限級selectTree類

WBOY
WBOY原創
2016-07-25 09:03:241089瀏覽
  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. ?>

复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn