我需要显示表格中的数据,并且每个条目都有一个父项,我的 php 代码如下所示:
function makeArbo($array, $currentParent = 0, $currLevel = 0, $prevLevel = -1, &$result = '')
{
if (is_array($array) && count($array) > 0)
{
foreach ($array as $item)
{
if ($currentParent == $item['idParent'])
{
if ($currLevel > $prevLevel)
$result .= '<ul>';
if ($currLevel == $prevLevel)
$result .= '</li>';
$result .= '<li>'.$item['name'].'</li>';
if ($currLevel > $prevLevel)
$prevLevel = $currLevel;
$currLevel++;
makeArbo($array, $item['id'], $currLevel, $prevLevel, $result);
$currLevel--;
}
}
if ($currLevel == $prevLevel)
$result .= '</li></ul>';
return $result;
}
}
echo makeArbo($array);
?>
}
我的桌子看起来像这样:
<?php
$array = array(
array(
'id' => 1,
'name' => 'Maths',
'idParent' => 0
),
array(
'id' => 2,
'name' => 'Topologie',
'idParent' => 1
),
array(
'id' => 3,
'name' => 'Algèbre',
'idParent' => 1
),
array(
'id' => 4,
'name' => 'Algèbre linéaire',
'idParent' => 3
),
array(
'id' => 5,
'name' => 'Arithmétique',
'idParent' => 3
),
array(
'id' => 6,
'name' => 'Thérorème de Bézout',
'idParent' => 5
),
array(
'id' => 7,
'name' => 'Informatique',
'idParent' => 0
),
array(
'id' => 8,
'name' => 'C-C++',
'idParent' => 7
),
array(
'id' => 9,
'name' => 'Les pointeurs',
'idParent' => 8
)
);
}
结果是完美的:
<ul>
<li>Maths</li>
<ul>
<li>Topologie</li>
<li>Algèbre</li>
<ul>
<li>Algèbre linéaire</li>
<li>Arithmétique</li>
<ul>
<li>Thérorème de Bézout</li>
</ul>
</ul>
</ul>
<li>Informatique</li>
<ul>
<li>C-C++</li>
<ul>
<li>Les pointeurs</li>
</ul>
</ul>
</ul>
但我需要将此代码从 php 转换为 javascript;
我尝试了这样的javascript代码:
function makeArbo(array,currentParent,currLevel, prevLevel, result)
{
if (typeof(currentParent)=='undefined'){
currentParent=0 ;
currLevel= 0 ;
prevLevel=-1 ;
result='';
}
if (array.length >0)
{
for (i=0;i< array.length;i++)
{
if (currentParent == array[i]['parentid'])
{
if (currLevel > prevLevel)
result += '<ul>';
if (currLevel == prevLevel)
result += '</li>';
result += '<li>'+ array[i]['name']+'</li>';
if (currLevel > prevLevel)
prevLevel = currLevel;
currLevel++;
result+=makeArbo (array,array[i]['id'], currLevel, prevLevel, result.valueOf());
currLevel--;
}
}
if (currLevel == prevLevel)
result += '</li></ul>';
return result ;
}
}
}
回报不好,我没有像我的第一个 php 代码一样的回报。我认为这是交叉引用(通过引用)的问题,因为在我的 php 代码中,结果是通过引用传递的 "&$result = ''" 。
有什么建议么?