1 回答
TA贡献1806条经验 获得超8个赞
这是答案,使用ref从多维数组创建嵌套数组
function makeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children')
{
$m = [];
foreach ($d as $e) {
isset($m[$e[$pk]]) ?: $m[$e[$pk]] = [];
isset($m[$e[$k]]) ?: $m[$e[$k]] = [];
$m[$e[$pk]][] = array_merge($e, [$c => &$m[$e[$k]]]);
}
return $m[$r]; // remove [0] if there could be more than one root nodes
}
function nested2ul($data)
{
$result = [];
if (sizeof($data) > 0) {
$result[] = '<ul>';
foreach ($data as $entry) {
$result[] = sprintf(
'<li>%s %s</li>',
$entry['name'],
nested2ul($entry['children'])
);
}
$result[] = '</ul>';
}
return implode($result);
}
$temp= makeRecursive($two_dimention);
echo nested2ul($temp);
输出
<ul>
<li>Home </li>
<li>Menu 1 </li>
<li>Menu 2
<ul>
<li>Menu 2.1
<ul>
<li>Menu 2.1.1 </li>
<li>Menu 2.1.2 </li>
</ul>
</li>
<li>Menu 2.2 </li>
</ul>
</li>
<li>Menu 3
<ul>
<li>Menu 3.1 </li>
</ul>
</li>
</ul>
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报