ThinkPHP之下拉树

物资种类表是个树状结构

   //读取物资种类数据,返回到页面
   //从数据库获取所有物资种类
   $mlist = D('MaterialCategory')->field('id,pid,name')->select();
   $tree = D('Common/Tree')->toFormatTree($mlist,'name');
   $treeoptions = array_column($tree,'title_show','id');
   $this->assign('treeoptions',option_selected($treeoptions,$categoryid));
public function toFormatTree($list,$title = 'title',$pk='id',$pid = 'pid',$root = 0){
        $list = list_to_tree($list,$pk,$pid,'_child',$root);
        $this->formatTree = array();
        $this->_toFormatTree($list,0,$title);
        return $this->formatTree;
}
/***/
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {

    $tree = array();// 创建Tree
    if(is_array($list)) {
        //第一步.把数值数组list转换为关联数组refer,用元素主键id来关联
        $refer = array(); // 创建基于主键的数组引用
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        //第二步:遍历数值数组
        foreach ($list as $key => $data) {
            // 判断某元素是否存在parent
            $parentId =  $data[$pid];
             //2.1 如果不存在parent,则给根节点增加一个元素
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{ /2.2 如果存在parent,给它的parent增加一个子节点
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

分析代码

<?php  

 /*$parent,$list,$refer,$tree 都是一体的,因为是引用*/ 

 $parent =& $refer[$parentId]; //引用

 $parent[$child][] =& $list[$key];//改变$parent,就相当于改变其他三个

 ?>
<?php 

private $formatTree; //用于树型数组完成递归格式的全局变量
/*把分好组的树在铺开*/
private function _toFormatTree($list,$level=0,$title = 'title') {
foreach($list as $key=>$val){
    $tmp_str=str_repeat("&nbsp;",$level*2);
    $tmp_str.="└";

    $val['level'] = $level;
    $val['title_show'] =$level==0?$val[$title]."&nbsp;":$tmp_str.$val[$title]."&nbsp;";
        // $val['title_show'] = $val['id'].'|'.$level.'级|'.$val['title_show'];
    if(!array_key_exists('_child',$val)){
        array_push($this->formatTree,$val);
    }else{
        $tmp_ary = $val['_child'];
        unset($val['_child']);
        array_push($this->formatTree,$val);
           $this->_toFormatTree($tmp_ary,$level+1,$title); //进行下一层递归
        }
    }
    return;
}
?>
posted on 2017-04-18 16:37  dreamstar  阅读(175)  评论(0编辑  收藏  举报