search
HomeBackend DevelopmentPHP Tutorial读取树状数据的方法

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

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),.....................

支持支持支持

不错的思路,代码蛮简洁

很好的方法 

嗯嗯,不错哦!

不错,值得看看

好东西,收藏了

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

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

直接用循环不就可以了?

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

学习,学习,谢谢

很好的资源.谢谢

初来乍到!回帖支持下

楼主幸苦了。谢谢分享此

好,呵呵呵呵呵

这是什么玩意

楼主幸苦了。值得学习

很好啊

真的很不错

学习,感谢楼主

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor