数据库表test
id  name  pid
1   a      0
2   b      1
3   c      1
4   d      2
5   e      2
6   f      3
7   g      4pid是父ID,即取id值
然后要输出一个树:
a
|-b
  |-d
    |-g
  |-e
|-c
  |-f不好意思,数据结构不会,算法不行...

解决方案 »

  1.   

    //数据集
    $result[0] = array('id'=>1,'pid'=>0,'name'=>'a',);
    $result[1] = array('id'=>2,'pid'=>1,'name'=>'b');
    $result[2] = array('id'=>3,'pid'=>1,'name'=>'c');
    $result[3] = array('id'=>4,'pid'=>2,'name'=>'d');
    $result[4] = array('id'=>5,'pid'=>2,'name'=>'e');
    $result[5] = array('id'=>6,'pid'=>3,'name'=>'f');
    $result[6] = array('id'=>7,'pid'=>4,'name'=>'g');
    //简易类
    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];
    //view
                    $str = str_repeat(" ",$deep*2)."|-";
                    $html[] ="{$str}{$v[$this->nodeName]}";    
                    if($this->treeArray[$t] ) 
                    {
                        $dp    = $deep + 1;
                        $html[]= $this->showTree( $t,$dp );
                    }
                }
            }
            return implode("<br/>",$html);
        }
    }
    $tree = new tree($result,'id','pid','name');
    echo $tree->showTree(0,0);
      

  2.   

    数据量有多少?
    你就整个copy这段代码过去会死循环?