搜索 |
<?php
namespace Think;
/**
* 无线分类类
*/
class Tree{
public $sqlPidName="pid"; //数据库字段pid
public $tableName="Department";//菜单的数据库表名
public $colName="name";//展示菜单时候的数据字段
public $aTid="id";//菜单的自增字段
/**
* 查找父级id下的数据
* @param integer $pid 父级id
* @return array 返回的数组
*/
private function getLoop($pid=0){
$deepSql=M($this->tableName);
$mysql=
$deepSql
->field(true)
->where(array($this->sqlPidName=>array("eq",$pid)))
->select(false);
if(!preg_match("/where/i",$mysql)){
return false;//防止没有正确配置数据库pid字段名称导致死循环
}
$datainfo=$deepSql
->field(true)
->where(array($this->sqlPidName=>array("eq",$pid)))
->select();
return $datainfo;
}
/**
* 获取第一级菜单
* @param int $pid 父级id
* @return array 返回数组
*/
private function getFirst($pid=0){
$deepSql=M($this->tableName);
$parent=$deepSql
->field(true)
->where(array($this->aTid=>array("eq",$pid)))
->select();
return $parent;
}
/**
* 获取菜单的数组
* @param integer $pid 父级ID
* @return array 数组
*/
public function getTree($pid=0){
$myResult=$this->getLoop($pid);
if(!$myResult){
return false;
}
if($pid==0){
return $this->deep_loop_child($myResult);
}else{
$return=$this->getFirst($pid);
$return[0]['childs']=$this->deep_loop_child($myResult);
}
return $return;
}
/**
* 循环寻找子菜单
* @param array &$result 要循环的数组
* @return array 返回的数组
*/
private function deep_loop_child(&$result){
if(!is_array($result)) return false;
foreach ($result as $key => $value) {
if($value){
$result[$key]['childs']=$this->getLoop($value[$this->aTid]);
if(count($result[$key]['childs'])==0){
unset($result[$key]['childs']);
}else{
$this->deep_loop_child($result[$key]['childs']);
}
}
}
return $result;
}
/**
* 前台展示树形结构
* @param array $data 数组数据
* @param int $type 默认为0;显示的是div结构加上js可以实现点击显示隐藏
* @param int $space 以select显示时候文字前面的空格数目
* @return str 返回的结果集
*/
public function showTree($data,$type="0",$space="0"){
$str="";
if($type!=0){
$space=$space+2;
foreach ($data as $key => $value) {
$str.="<option value={$value[$this->colName]}>".str_repeat(" ",$space)."|--".$value[$this->colName]."</option>";
if($value['childs']){
$str.=$this->showTree($value['childs'],$type,$space);
}
}
}else{
$str.="<ul>";
foreach ($data as $key => $value) {
$str.="<li>".$value[$this->colName];
if($value['childs']){
$str.=$this->showTree($value['childs']);
}
$str.="</li>";
}
$str.= "</ul>";
}
return $str;
}
}