问题: 我想不出对我的具体情况使用递归函数的方式。
情况:
Mysql DB id | root | name | 在root显示给女巫类别的地方这是子类别。
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函数才能将其全部打印出来?
怎么样:
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>'; }
希望有帮助吗?