gpt4 book ai didi

php - 在 PHP 中递归期间显示子类别并将类添加到列表

转载 作者:行者123 更新时间:2023-11-29 20:05:59 24 4
gpt4 key购买 nike

我正在使用递归函数在 PHP 中显示类别和子类别。在MySQL数据库表中,有3列:

cat_id, parent_id, cat_name 

但是,我应该继续跟踪无序列表,以便添加类以使用 jQuery 制作下拉菜单。因此,HTML 代码应如下所示:

<ul>
<li class = "dropdown"><a href = "#">Parent 1</a>
<ul class = "sub-menu">
<li><a href = "#">Sub 1</a></li>
<li class = "dropdown">
<a href = "#">Sub 2</a>
<ul class = "sub-menu">
<li><a href = "#">Sub 2.1</a></li>
<li><a href = "#">Sub 2.2</a></li>
<li><a href = "#">Sub 2.3</a></li>
</ul>
</li>
<li><a href = "#">Sub 3</a></li>
<li><a href = "#">Sub 4</a></li>
<li><a href = "#">Sub 5</a></li>
</ul>
</li>
<li><a href = "#">Parent 2</a></li>
<li><a href = "#">Parent 3</a></li>
<li><a href = "#">Parent 4</a></li>
</ul>

我正在使用的递归函数:

$query = "select * from  categories";$result = $conn->query($query); $cats = array();while($cat = $result->fetch_assoc()){$cats_ID[$cat['cat_id']][] = $cat;$cats[$cat['parent_id']][$cat['cat_id']] = $cat;}

function build_tree($cats,$cat_id,$only_parent = false){
if(is_array($cats) and isset($cats[$cat_id])){
$tree = "<ul>\n";

if($only_parent==false){
foreach($cats[$cat_id] as $cat){
$tree .= '<li><a href = "#">'.$cat['cat_name'];
$tree .= build_tree($cats,$cat['cat_id']);
$tree .= "</a></li>\n";
}
}

$tree .= "</ul>";
}
else return null;

return $tree;
}

我如何跟踪 ul 列表?

最佳答案

这应该像我在上面的评论中建议的那样通过添加 $深度 参数来实现。

$query = "select * from  categories";
$result = $conn->query($query);
$cats = array();
while($cat = $result->fetch_assoc()){
$cats_ID[$cat['cat_id']][] = $cat;
$cats[$cat['parent_id']][$cat['cat_id']] = $cat;
}

//added a depth argument that defaults to 1
function build_tree($cats,$cat_id,$only_parent = false, $depth=1){
if(is_array($cats) and isset($cats[$cat_id])){
//check if depth is > 1, output class, else, no class.
if($depth > 1){
$tree = "<ul class='sub-menu'>\n";
} else {
$tree = "<ul>\n";
}

if($only_parent==false){
foreach($cats[$cat_id] as $cat){
//get the recursion first
//adjusted recursive call to include depth+1.
$tmp = build_tree($cats,$cat['cat_id'],$only_parent,$depth+1);

//if we are at the first depth and there is child content
if($depth == 1 && is_null($tmp)){
//add the dropdown class
$tree .= '<li class="dropdown"><a href = "#">'.$cat['cat_name'];
} else {
//no dropdown class
$tree .= '<li><a href = "#">'.$cat['cat_name'];
}
//now append the recursion
$tree .= $tmp;
$tree .= "</a></li>\n";
}
}
$tree .= "</ul>";
}
else return null;
return $tree;
}

您应该能够用这个新函数替换您的函数,并且一切都应该正常工作,因为新添加的参数具有默认值。

关于php - 在 PHP 中递归期间显示子类别并将类添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349757/

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