PHP树结构

最近略研究了下PHP,树结构

<?php 
//数据库记录
$result[0] = array('id'=>1,'pid'=>0,'name'=>'aaa',);
$result[1] = array('id'=>2,'pid'=>0,'name'=>'bbb');
$result[2] = array('id'=>3,'pid'=>2,'name'=>'b1');
$result[3] = array('id'=>4,'pid'=>1,'name'=>'a1');
$result[4] = array('id'=>5,'pid'=>2,'name'=>'b2');
$result[5] = array('id'=>6,'pid'=>3,'name'=>'b11');
$result[6] = array('id'=>7,'pid'=>3,'name'=>'b12');
$result[7] = array('id'=>8,'pid'=>0,'name'=>'c1');
//简易类
class tree
{
    function tree($rs,$idName,$pidName,$nodeName)
    {
        $this->idName    = $idName;
        $this->nodeName = $nodeName;
        $tree = array();
        foreach((array)$rs as $k=>$v)
        {
            $tree[$v[$pidName]][] = $v;
        }

        $this->treeArray = $tree;
    }
    function showTree($root,$deep)
    {
        if( $this->treeArray[$root] )
        {
            foreach($this->treeArray[$root] as $k=>$v)
            {
                $t = $v[$this->idName];
                $str   = str_repeat("&nbsp;",$deep*4)."|-".str_repeat("-",$deep);
                $html ="{$str}{$v[$this->nodeName]}<br/>";
              
                if($this->treeArray[$t] )
                {
                $gx = $deep + 1;
                $this->showTree( $t,$gx );
                }
            }
        }
                return $html;
    }
}
$tree = new tree($result,'id','pid','name');
 $tree->showTree(0,0);
?>

 

posted @ 2013-06-21 10:13  Tiger..虎  阅读(565)  评论(0编辑  收藏  举报