我有一个将子元素添加到元素中的类,我想通过递归函数将这些元素显示在UL和LI中
我创建了一个函数,但是我以前从未做过递归,显然我做错了:D 我设法展示了可以的父母的孩子,如果可以的话,我可以显示孩子的父母
已经创建的类:
private static IWaveIn ActiveMicrophone = new WasapiCapture(ActiveMicrophoneDevice);
ActiveMicrophone.DataAvailable += OnMicrophoneDataAvailableAsync;
...
private async void OnMicrophoneDataAvailableAsync(object sender, WaveInEventArgs e)
{
MemoryStream micStream = new MemoryStream();
micStream.Write(e.Buffer, 0, e.BytesRecorded);
micStream.Position = 0;
var inputStream = new RawSourceWaveStream(micStream, ActiveMicrophone.WaveFormat);
WaveFormat outputFormat = new WaveFormat(8000, 8, 1);
using (var resampler = new MediaFoundationResampler(inputStream, outputFormat))
{
MemoryStream outputStream = new MemoryStream();
WaveFileWriter.WriteWavFileToStream(outputStream, resampler);
// Do something with outputStream?
}
}
在index.php中创建元素:
class MenuElement {
public $id;
public $children = array();
public function __construct($id)
{
$this->id = $id;
}
public function addChild(MenuElement $menuElement)
{
array_push($this->children, $menuElement);
}
}
我的函数只是在addChild下面:
$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>
我知道了
答案 0 :(得分:0)
快到了!您只需要在代码的第一个版本中对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;
}