zl程序教程

您现在的位置是:首页 >  后端

当前栏目

php无限级SelectTree类

PHP 无限
2023-06-13 09:14:09 时间
复制代码代码如下:

/*
author:nick
date:2009.05.17
功能:生成SeletTree
属性:
$result结果集
$id_field自身id字段
$parent_field父类id字段
$option_text选项显示名称
$select_name下拉菜单的名称
$elected默认选中
$no_top是否需要顶层选项
$level层深度
$parent_id同层中的id
*/
classSelectTree{
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();
}
/*
功能:返回Tree二维数组
*/
functiongetArray(){
$arrays=array();
while($row=mysql_fetch_array($this->result)){
$arrays[$row[$this->parent_field]][$row[$this->id_field]]=$row;
}
return$arrays;
}
/*
功能:获取SelectTree
*/
functiongetSelectTree(){
$tree="<selectname="".$this->select_name."">";
if($no_top){
$tree.="<optionvalue="0">最顶层</option>";
}
self::buildTree($this->getarray,&$tree,$this->id_field,$this->option_text,$this->selected,$this->level,$this->parent_id);//生成树状结构
$tree.="</select>";
return$tree;
}
/*
功能:递归构建树状结构
*/
functionbuildTree($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.="";//选项缩进深度
foreach($array[$parent_id]as$key=>$value){
if($value[$option_value]==$selected){
$tree.="<optionvalue="".$value[$option_value].""selected="selected">".$space.$value[$option_text]."</option>";
}else{
$tree.="<optionvalue="".$value[$option_value]."">".$space.$value[$option_text]."</option>";
}
$tree.=self::buildTree($array,&$tree,$option_value,$option_text,$selected,$level+1,$key);
}
}else{
$tree.="";
}
}
}
/****************************************************************************/
header("CONTENT-TYPE:TEXT/HTML;CHARSET=UTF-8");
mysql_connect("localhost","root","root");
mysql_select_db("tree");
mysql_query("setnamesutf8");
$result=mysql_query("select*fromtvmenu");
$tree=newSelectTree($result,"id","bid","name","tree");
echo$tree->getSelectTree();