>백엔드 개발 >PHP 튜토리얼 >读取树状数据的方法

读取树状数据的方法

WBOY
WBOY원래의
2016-06-23 13:52:49871검색

读取树状数据的方法
一般在读取用“邻接列表算法”组织的数据时,需要使用递归逐层读取
或者读取数据到数组,然后用递归或非递归的方法再行处理
这里介绍一种边读边生成“树状”数组的方法,希望对你有用

mysql_connect();//测试数据$sql =<<< SQLselect * from (  select '1' as id, '0' as pid, 'Food' as title  union all select '2', '1', 'Fruit'  union all select '3', '2', 'Red'  union all select '4', '3', 'Cherry'  union all select '5', '2', 'Yellow'  union all select '6', '5', 'Banana'  union all select '7', '1', 'Meat'  union all select '8', '7', 'Beef'  union all select '9', '7', 'Pork'  ) t  order by pid, idSQL;$rs = mysql_query($sql);$res = array(); //结果数组$ind = array(); //索引数组while($row = mysql_fetch_assoc($rs)) {  list($id, $pid) = array_values($row);   $ind[$id] = $row;  if(isset($ind[$pid])) $ind[$pid]['child'][$id] =& $ind[$id]; //构造索引  if($pid == 0) $res[$id] =& $ind[$id]; //转存根节点组}echo '<xmp>' . print_r($res, 1);
Array
(
    [1] => Array
        (
            [id] => 1
            [pid] => 0
            [title] => Food
            [child] => Array
                (
                    [2] => Array
                        (
                            [id] => 2
                            [pid] => 1
                            [title] => Fruit
                            [child] => Array
                                (
                                    [3] => Array
                                        (
                                            [id] => 3
                                            [pid] => 2
                                            [title] => Red
                                            [child] => Array
                                                (
                                                    [4] => Array
                                                        (
                                                            [id] => 4
                                                            [pid] => 3
                                                            [title] => Cherry
                                                        )

                                                )

                                        )

                                    [5] => Array
                                        (
                                            [id] => 5
                                            [pid] => 2
                                            [title] => Yellow
                                            [child] => Array
                                                (
                                                    [6] => Array
                                                        (
                                                            [id] => 6
                                                            [pid] => 5
                                                            [title] => Banana
                                                        )

                                                )

                                        )

                                )

                        )

                    [7] => Array
                        (
                            [id] => 7
                            [pid] => 1
                            [title] => Meat
                            [child] => Array
                                (
                                    [8] => Array
                                        (
                                            [id] => 8
                                            [pid] => 7
                                            [title] => Beef
                                        )

                                    [9] => Array
                                        (
                                            [id] => 9
                                            [pid] => 7
                                            [title] => Pork
                                        )

                                )

                        )

                )

        )

)


回复讨论(解决方案)

支持版主

工作几年,一直用这用处理无限分类,这个类不是我写的,希望作者来认领,有时也要扩展一些方法。但基础方法已经足够了

class Tree{    public $data=array();    public $cateArray=array();    function Tree()    {    }    function setNode ($id, $parent, $value)    {	    $parent = $parent?$parent:0;	    $this->data[$id] = $value;	    $this->cateArray[$id] = $parent;    }    function getChildsTree($id=0)    {	    $childs=array();	    foreach ($this->cateArray as $child=>$parent)	    {		    if ($parent==$id)		    {		    	$childs[$child]=$this->getChildsTree($child);		    }	    }	    return $childs;    }    function getParentsTree($id=0)    {	    $parents=array();	    foreach ($this->cateArray as $child=>$parent)	    {		    if ($child ==$id)		    {		    	$parents[$parent]=$this->getParentsTree($parent);		    }	    }	    return $parents;    }    function getChilds($id=0)    {	    $childArray=array();	    $childs=$this->getChild($id);	    foreach ($childs as $child)	    {		    $childArray[]=$child;		    $childArray=array_merge($childArray,$this->getChilds($child));	    }	    return $childArray;    }        function getChild($id)    {	    $childs=array();	    foreach ($this->cateArray as $child=>$parent)	    {	    if ($parent==$id)	    {	    	$childs[$child]=$child;	    }	    }	    return $childs;    }        function getParents($id)    {	    $parentArray=array();	    $parents=$this->getParent($id);	    foreach ($parents as $parent)	    {		    $parentArray[]=$parent;		    $parentArray=array_merge($parentArray,$this->getParents($parent));	    }	    return $parentArray;    }        function getParent($id)    {	    $parents=array();	    foreach ($this->cateArray as $child=>$parent)	    {	    if ($child==$id)	    {	    	$parents[$parent]=$parent;	    }	    }	    return $parents;    }    //单线获取父节点    function getNodeLever($id)    {	    $parents=array();	    if (key_exists($this->cateArray[$id],$this->cateArray))	    {		    $parents[]=$this->cateArray[$id];		    $parents=array_merge($parents,$this->getNodeLever($this->cateArray[$id]));	    }	    return $parents;    }    function getLayer($id,$preStr='|-')    {    	return str_repeat($preStr,count($this->getNodeLever($id)));    }    function getValue ($id)    {    	return $this->data[$id];    } // end func}

=&  这个是运算符?

很好的算法,参考一下

不错,值得借鉴。

感谢版主分享

支持版主

=&  这个是运算符? 

方法不错,收藏

初学者,看的有点蒙

好东西!!

研究盐?鸡,好东西

很好的方法 

正在找这捏~谢楼主~

 我以为语言都是相通的,但是还是看不懂,看样功力不够

还好 谢谢贴主赐教 。。。

版主大哥~~再把你这个输出的树状数组转成以ID排序的二维数组呢?
Array([1]=>([id] => 1
             [pid] => 0
             [title] => Food),
     [2]=>]=>([id] => 2
             [pid] => 0
             [title] => Fruit),.....................

支持支持支持

不错的思路,代码蛮简洁

很好的方法 

嗯嗯,不错哦!

不错,值得看看

好东西,收藏了

树状数据存在数据库中吗?

看了很久不明白,为什么要这样来查出数据?

直接用循环不就可以了?

难者不会,会者不难的啊!

学习,学习,谢谢

很好的资源.谢谢

初来乍到!回帖支持下

楼主幸苦了。谢谢分享此

好,呵呵呵呵呵

这是什么玩意

楼主幸苦了。值得学习

很好啊

真的很不错

学习,感谢楼主

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.