gpt4 book ai didi

mysql - 使用 mysqli 查询从树形菜单中查找子级的深度

转载 作者:行者123 更新时间:2023-11-29 22:07:30 25 4
gpt4 key购买 nike

MYSQL TABLE

|id|parent_id|
|1 | 0| <- depth 1
|2 | 1| <- depth 2
|3 | 1| <- depth 2
|4 | 2| <- depth 3
|5 | 3| <- depth 3
|6 | 4| <- depth 4

我需要找出 id 4 的深度,在上面的例子中是 3

是否可以通过一个 mysqli 查询来完成此操作?如果没有,我该如何使用多个 mysqli 查询来做到这一点?

非常感谢。

已编辑

function find_depth($id, $depth = 0){
global $con;
$query = "SELECT * from table WHERE `id` = $id";
if ($result = $con->query($query)){
if (mysqli_num_rows($result) == 1){
$row = $result->fetch_array();
$depth = $depth + 1;
find_level($row['parent_id'], $depth);
} else {
return $depth;
}
}
}

find_depth('4')

给我3

但是,我仍在寻找更好的方法来实现这一目标

最佳答案

如果表不大,只能对DB进行一次查询

function find_depth($id, $depth = 0) {
global $con;
$temp = array();
$query = "SELECT * from table";
if ($result = $con->query($query)) {
while($row = $result->fetch_array())
$temp[$row['id']] = $row['parent_id'];
do { $depth = $depth + 1; } while($id = $temp[$id]);
}
return $depth;
}

find_depth('4');

关于mysql - 使用 mysqli 查询从树形菜单中查找子级的深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32014424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com