日期:2014-05-17 浏览次数:20755 次
//数据库记录
$result[0] = array('id'=>1,'pid'=>0,'name'=>'公司1',);
$result[1] = array('id'=>2,'pid'=>0,'name'=>'公司2');
$result[2] = array('id'=>3,'pid'=>2,'name'=>'公司2的子公司1');
$result[3] = array('id'=>4,'pid'=>1,'name'=>'公司1的子公司1');
$result[4] = array('id'=>5,'pid'=>2,'name'=>'公司2的子公司2');
$result[5] = array('id'=>6,'pid'=>3,'name'=>'公司2的子公司1的子公司1');
$result[6] = array('id'=>7,'pid'=>3,'name'=>'公司2的子公司1的子公司2');
//简易类
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(" ",$deep*4)."|-".str_repeat("-",$deep);
$html .="{$str}{$v[$this->nodeName]}<br/>";
if($this->treeArray[$t] )
{
$gx = $deep + 1;
$html .= $this->showTree( $t,$gx );
}
}
}
return $html;
}
}
$tree = new tree($result,'id','pid','name');
echo $tree->showTree(0,0);
------解决方案--------------------