我有一个Json菜单,我喜欢它: -
[{"slug":"index.php","name":"Home"},{"slug":"aboutus","name":"About us","children":[{"slug":"eims","name":"Eims"},{"slug":"vision","name":"Vision"}]},{"slug":"trash","name":"Trash","children":[{"slug":"ways","name":"Ways"},{"slug":"requ","name":"Requ"}]}]
现在我需要将这个json转换为这样的菜单: -
<li><a href="./" >Home</a></li>
<li><a href="container.php?fun=aboutus" >About us</a>
<ul>
<li><a href="container.php?fun=eims">Eims</a></li>
<li><a href="container.php?fun=vision">Vision</a></li>
</ul>
</li>
<li><a href="container.php?fun=trash">Trash</a>
<ul>
<li><a href="container.php?fun=ways">Ways</a></li>
<li><a href="container.php?fun=requ">Requ</a></li>
</ul>
</li>
</li>
我该怎么做?
答案 0 :(得分:0)
检查一下。
<?php
function parseNodes($nodes) {
$ul = "<ul>\n";
foreach ($nodes as $node) {
$ul .= parseNode($node);
}
$ul .= "</ul>\n";
return $ul;
}
function parseNode($node) {
$li = "\t<li>";
$li .= '<a href="'.$node->slug.'">'.$node->name.'</a>';
if (isset($node->children)) { $li .= parseNodes($node->children); }
$li .= "</li>\n";
return $li;
}
$json = '[{"slug":"index.php","name":"Home"},{"slug":"aboutus","name":"About us","children":[{"slug":"eims","name":"Eims"},{"slug":"vision","name":"Vision"}]},{"slug":"trash","name":"Trash","children":[{"slug":"ways","name":"Ways"},{"slug":"requ","name":"Requ"}]}]';
$nodes = json_decode($json);
$html = parseNodes($nodes);
echo $html;
?>