读取树状数据的方法
读取树状数据的方法
一般在读取用“邻接列表算法”组织的数据时,需要使用递归逐层读取
或者读取数据到数组,然后用递归或非递归的方法再行处理
这里介绍一种边读边生成“树状”数组的方法,希望对你有用
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);
(
[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),.....................
支持支持支持
不错的思路,代码蛮简洁
很好的方法
嗯嗯,不错哦!
不错,值得看看
好东西,收藏了
树状数据存在数据库中吗?
看了很久不明白,为什么要这样来查出数据?
直接用循环不就可以了?
难者不会,会者不难的啊!
学习,学习,谢谢
很好的资源.谢谢
初来乍到!回帖支持下
楼主幸苦了。谢谢分享此
好,呵呵呵呵呵
这是什么玩意
楼主幸苦了。值得学习
很好啊
真的很不错
学习,感谢楼主

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual
