问题:我无法想办法对我的具体情况做一个递归函数。
情况:
Mysql DB
id | root | name |
root
显示巫婆类别的地方,这是子类别。
HTML应该如何显示:
<li><a href="#"><p class="Tier0">Datori</p></a>
<ul style="display: block">
<li><a href="#"><p class="Tier1">Cookies</p></a></li>
<li><a href="#"><p class="Tier1">Events</p></a></li>
<li><a href="#"><p class="Tier1">Forms</p></a></li>
<li><a href="#"><p class="Tier1">Games</p></a></li>
<li><a href="#"><p class="Tier1">Images</p></a>
<ul>
<li><a href="#"><p class="Tier2">CSS</p></a></li>
<li><a href="#"><p class="Tier2">JavaScript</p></a></li>
<li><a href="#"><p class="Tier2">JQuery</p></a></li>
</ul>
</li>
<li><a href="#"><p class="Tier1">Navigations</p></a>
<ul>
<li><a href="#"><p class="Tier2">CSS</p></a></li>
<li><a href="#"><p class="Tier2">JavaScript</p></a></li>
<li><a href="#"><p class="Tier2">JQuery</p></a></li>
</ul>
</li>
<li><a href="#"><p class="Tier1">Tabs</p></a></li>
</ul>
</li>
<li><a href="#"><p class="Tier0">Washing Machines</p></a>
我需要什么样的PHP函数来打印出来?
答案 0 :(得分:10)
怎么样:
function recurse($categories, $parent = null, $level = 0)
{
$ret = '<ul>';
foreach($categories as $index => $category)
{
if($category['root'] == $parent)
{
$ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>';
$ret .= $this->recurse($categories, $category['id'], $level+1);
$ret .= '</li>';
}
}
return $ret . '</ul>';
}
此函数要求您首先在数据库中查询可用类别的完整列表,并假定您的根类别的值为null,但可以将该函数更改为接受-1或0,具体取决于当前架构的工作方式
$categories = { get from database into an multi-dimensional array };
$Tree = $this->recurse($categories);
echo $Tree;
您可以考虑执行以下操作,以防止父母没有子女时出现任何空的UL:
function recurse($categories, $parent = null, $level = 0)
{
$ret = '<ul>';
foreach($categories as $index => $category)
{
if($category['root'] == $parent)
{
$ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>';
$sub = $this->recurse($categories, $category['id'], $level+1);
if($sub != '<ul></ul>')
$ret .= $sub;
$ret .= '</li>';
}
}
return $ret . '</ul>';
}
但是,最好的解决方案是选择您的数据以包含一个列,其中包含每个类别有多少个子类别。
select Category.*, (select count(distinct c1.id) from Category as c1 where c1.root = Category.id) as ChildCount from Category
你的职能是:
function recurse($categories, $parent = null, $level = 0)
{
$ret = '<ul>';
foreach($categories as $index => $category)
{
if($category['root'] == $parent)
{
$ret .= '<li><a href="#"><p class="Tier' . $level . '">' . $category['name'] . '</p></a>';
if($category['ChildCount'] > 0)
$ret .= $this->recurse($categories, $category['id'], $level+1);
$ret .= '</li>';
}
}
return $ret . '</ul>';
}
希望有帮助吗?