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[]
I almacenate this info in an array called 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 中的简单递归树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP/MySQL 中的简单递归树
基础教程推荐
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01