我已经实现了以递归方式向页面打印类别树:
foreach ($categories as $category) {
$tree .='<li>'.$category->title.'';
if(count($category->childs)) {
$tree .=$this->childView($category);
}
}
$tree .='<ul>';
return view('categoryTreeview',compact('categories','allCategories','tree'));
}
public function childView($category){
$html ='<ul>';
foreach ($category->childs as $arr) {
if(count($arr->childs)){
$html .='<li>'.$arr->title.'';
$html.= $this->childView($arr);
}else{
$html .='<li>'.$arr->title.'';
$html .="</li>";
}
}
$html .="</ul>";
return $html;
}
对于数据库结构:id|title|parent_id
现在我需要实现一种迭代方法来打印页面的类别树,到目前为止我还没有找到解决方案。
我也尝试过:
function buildTree($categories) {
$childs = array();
foreach($categories as $category)
$childs[$category->parent_id][] = $category;
foreach($categories as $category) if (isset($childs[$category->id]))
$category->childs = $childs[$category->id];
return $childs[0];
}
$treez = buildTree($categories);
但我也不知道如何非递归地使用这些数据。
有人能引导我走上正确的道路吗?也许我应该将foreach
循环与某种条件结合起来?