递归函数菜单树,没有DB



>我有一个类将子元素添加到元素中,我想将这些元素显示到具有递归函数的 UL 和 LI 中

我创建了一个函数,但我以前从未做过递归,而且我显然做错了:D 我设法显示我可以显示父母的孩子,以及如果的孩子,但我可以走得更远

已创建的类:


class MenuElement {
public $id;
public $children = array();
public function __construct($id)
{
$this->id = $id;
}
public function addChild(MenuElement $menuElement)
{
array_push($this->children, $menuElement);
}
}

索引中元素的创建.php :


$listRecursive1 = new ListRecursive(1);
$listRecursive11 = new ListRecursive(11);
$listRecursive12 = new ListRecursive(12);
$listRecursive121 = new ListRecursive(121);
$listRecursive122 = new ListRecursive(122);
$listRecursive123 = new ListRecursive(123);
$listRecursive1211 = new ListRecursive(1211);
$listRecursive121->addChild($listRecursive1211);
$listRecursive12->addChild($listRecursive121);
$listRecursive12->addChild($listRecursive122);
$listRecursive12->addChild($listRecursive123);
$listRecursive1->addChild($listRecursive11);
$listRecursive1->addChild($listRecursive12);

我的函数只是在下面添加儿童:


public function createList()
{
$html = "";
foreach ($this->children as $child) 
{
$html .= "<ul><li>" . $child->id;
//If the element have a child I create a new UL
if ($child->children) {
$html .= "<ul><li>" . $child->id;
$html .= "</li></ul>";
}
$html .= "</li></ul>";
}
//Return the result
return $html;
}

我想像这样显示列表:

<ul>
<li>1
<ul>
<li>11</li>
<li>12
<ul>
<li>121
<ul>
<li>1211</li>
</ul>
</li>
<li>122</li>
<li>123</li>
</ul>
</li>   
</ul>
</li>
</ul>

但这就是我得到的:

<ul>
<li>11</li>
</ul>
<ul>
<li>12
<ul>
<li>12</li>
</ul>
</li>
</ul>

编辑:

我试试这个:


public function createList()
{
$html = "";
foreach ($this->children as $child) {
$html .= "<ul><li>" . $child->id;
//If the element have a child I create a new UL
if ($child->children) {
echo  "<ul>";
$child->createList();
echo "</ul>";
}
$html .= "</li></ul>";
}
//Return the result
echo $html;
}

我得到了

      • 1211
    • 121
    • 122
    • 123
  • 11
  • 12

快到了!您只需要在代码的第一个版本中对createList()进行递归调用,并将其结果附加到$html

public function createList()
{
$html = "";
foreach ($this->children as $child) {
$html .= "<ul><li>" . $child->id;
if ($child->children) { 
$html .= $child->createList();
}
$html .= "</li></ul>";
}
return $html;
}

最新更新