我有一个数组,其中的数据嵌套如下(只是一个简化的例子,因为它必须是"无尽的",因为每个家谱可以超过X代):
Array
(
[id] => 121
[name] => Very Important Dogs Bowey Showey
[gen] => 0
[mother] => Array
(
[id] => 128
[name] => Veridique Of Winners
[gen] => 1
[mother] =>
[father] =>
)
[father] => Array
(
[id] => 124
[name] => Rosickys Robocopico
[gen] => 1
[mother] => Array
(
[id] => 75
[name] => Astro Spice
[gen] => 2
[mother] =>
[father] =>
)
[father] => Array
(
[id] => 62
[name] => Your King of the World
[gen] => 2
[mother] =>
[father] =>
)
)
)
我尝试了这个PHP函数,但没有成功,因为它确实遍历了每个数组并创建了一个项目符号,但我不能隔离"name"answers"ID",因为它们都在一起。
function recurseTree($var){
$out = '<li>';
foreach($var as $v){
if(is_array($v)){
$out .= '<ul>'.recurseTree($v).'</ul>';
}else{
$out .= $v;
}
}
return $out.'</li>';
}
echo '<ul>'.recurseTree($familytree).'</ul>';
结果是这样的:
- 121Very Important Dogs' Bowey Showey0
- 128Veridique Of Winners1
- 124Rosicky's Robocopico1
- 75Astra's Spice2
- 62Lazhar's King of the World2
它给了我一个不可用的字符串。相反,我想使用类似$v['id']
的东西来获取id(并创建一个href
链接)和名称,如$v['name']
…但是如何? !
我要的格式:
<ul>
<li><span>Mother</a></span>
<ul>
<li><span><a href="#">Grandmother</a></span>
<ul>
<li><span>Grand-Grandmother</span></li>
<li><span>Grand-Grandfather</span></li>
</ul>
</li>
<li><span><a href="#">Grandfather</a></span>
</ul>
</li>
<li><span>Father</a></span>
<ul>
<li><span><a href="#">Grandmother</a></span>
<li><span><a href="#">Grandfather</a></span>
</ul>
</li>
</ul>
你可以这样做:
function recurseTree($var)
{
$out = '<li>';
foreach($var as $k => $v)
{
if(is_array($v))
{
$out .= '<ul>'.recurseTree($v).'</ul>';
}
else
{
switch($k)
{
case 'id':
$out .= 'id='.$v;
break;
case 'name':
$out .= 'name='.$v;
break;
}
}
}
return $out.'</li>';
}
echo '<ul>'.recurseTree($familytree).'</ul>';
因为你的数组是关联的,并且似乎遵循一致的格式,我认为你实际上可以在不使用循环的情况下做到这一点。这将使格式化更容易。
function recurseTree($var) {
if ($var) {
$link = '<span><a href="link.php?id='. $var['id']. '">'. $var['name']. '</a></span>';
$parents = '';
if ($var['mother'] || $var['father']) {
$parents = '<ul>'. recurseTree($var['mother']). recurseTree($var['father']). '</ul>';
}
return "<li>$link$parents</li>";
}
}
echo '<ul>' . recurseTree($familytree) . '</ul>';