怎么样:
function recurse($categories, $parent = null, $level = 0){ $ret = '<ul>'; foreach($categories as $index => $category) { if($category['root'] == $parent) { $ret .= '<li><a href="#"><p >' . $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 >' . $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 >' . $category['name'] . '</p></a>'; if($category['ChildCount'] > 0) $ret .= $this->recurse($categories, $category['id'], $level+1); $ret .= '</li>'; } } return $ret . '</ul>';}
希望有帮助吗?
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)