PHP/MySQL中的简单递归树 [英] Simple recursive tree in PHP / MySQL
本文介绍了PHP/MySQL中的简单递归树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在MySQL中有此表:
I have this table in MySQL:
id name mother
1 grandma 0
2 myuncle 1
3 mymom 1
4 me 3
5 mysister 3
6 myson 4
7 new_grandma_son 1
我在名为data[]
$data=array(
array("id"=>1,"name"=>"grandma", "mother"=>0),
array("id"=>2,"name"=>"myuncle", "mother"=>1),
array("id"=>3,"name"=>"mymom", "mother"=>1),
array("id"=>4,"name"=>"me", "mother"=>3),
array("id"=>5,"name"=>"mysister", "mother"=>3),
array("id"=>6,"name"=>"myson", "mother"=>4),
array("id"=>7,"name"=>"new_grandma_son","mother"=>1)
);
为了创建家谱,我正在使用此递归函数:
And for make a family tree I am using this recursive function:
function tree($data, $mom = 0, $level = 0){
foreach ($data as $row){
if ($row['mother'] == $mom) {
echo str_repeat("-", $level).$row['name']."<br>";
tree($data, $row['id'], $level);
}
else $level++;
}
}
当我调用函数tree($data);
时,它显示如下:
When I call the function tree($data);
it shows this:
grandma
-myuncle (level 1)
-mymom
----me (level 4??)
---------myson (level 9??)
----mysister
----new_grandma_son (level 4??)
我在else $level++;
中有一个错误,因为在$row['mother'] != $mom
时添加了级别,遍历了所有行,但是我不知道该怎么做.
有谁知道?谢谢.
I have the mistake in the else $level++;
, because is adding levels when $row['mother'] != $mom
, going through all the rows, but I don't know how to make it.
Anyone knows? Thank you.
解决方案(作者Frits van Campen):
tree($data, $row['id'], $level+1);
// (eliminate this else $level++; )
谢谢!
推荐答案
function tree($data,$mom=0,$level=0){
foreach($data as $row){
if($row['mother']==$mom){
echo str_repeat("-",$level).$row['name']."<br>";
tree($data,$row['id'],$level+1);
}
}
}
我认为这可以修复您的代码.您可以提供$data
以便我对其进行测试吗?
I think this fixes your code. Can you supply the $data
so I can test it?
这篇关于PHP/MySQL中的简单递归树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文