/*
author: nick Function: Generate SeletTree Attribute: $result result set $id_field own id field $parent_field parent class id field $option_text Option display name $select_name The name of the drop-down menu $elected Default selected $no_top Whether top-level options are required $level layer depth $parent_id id in the same layer */ class SelectTree{ public $result; public $ select_name; public $option_text; public $elected; public $id_field; public $parent_field; public $no_top; public $level; public $parent_id; public $getarray; function __construct($result,$ id_field,$parent_field,$option_text,$select_name='',$elected=0,$no_top=0,$level=0,$parent_id=0){ $this->result =$result;
$this- >id_field =$id_field;
$this->parent_field =$parent_field;
$this->option_text =$option_text;
$this->select_name =$select_name;
$this->elected =$elected ;
$this->no_top =$no_top;
$this->level =$level;
$this->parent_id =$parent_id;
$this->getarray =self::getArray();
}
/*
Function: Return Tree two-dimensional array
*/
function getArray(){
$arrays=array();
while($row=mysql_fetch_array($this-> ;result)){
$arrays[$row[$this->parent_field]][$row[$this->id_field]]=$row;
}
return $arrays;
}
/*
Function: Get SelectTree
*/
function getSelectTree(){
$tree = '';
if( $no_top){
$tree .= 'Topmost ';
}
self::buildTree($this->getarray,&$tree,$this ->id_field,$this->option_text,$this->selected,$this->level,$this->parent_id); //Generate a tree structure
$tree .= '
return $tree;
}
/*
Function: Recursively build a tree structure
*/
function buildTree($array,&$tree,$option_value,$option_text, $selected,$level=0,$parent_id=0){
if(is_array($array[$parent_id])){
for($i=0;$i<$level;$i++) $space .= ' '; //Option indentation depth foreach($array[$parent_id] as $key => $value){
if($value[$option_value] == $selected){
$tree .= '< ;option value="'.$value[$option_value].'" selected="selected">'.$space.$value[$option_text]."";
}else{
$tree .= ''.$space.$value[$option_text]." ";
}
$tree .=self ::buildTree($array,&$tree,$option_value,$option_text,$selected,$level+1,$key);
}
}else{
$tree .= '';
}
}
}< ;/p>
/*----------*/
header("CONTENT-TYPE:TEXT/HTML;CHARSET=UTF-8");
mysql_connect("localhost", "root","root");
mysql_select_db("tree");
mysql_query('set names utf8');
$result = mysql_query("select * from tvmenu");
$tree=new SelectTree($result ,'id','bid','name','tree');
echo $tree->getSelectTree();
?>
Copy code