我有一个这样的 JSON:
{
"name":"Tree",
"id":"999999",
"is_open":true,
"children": [
{
"name":"Tree Step 1",
"id":"1",
"is_open":true,
"children":[
{
"name":"Tree Step 1.1",
"id":"1"
},
{
"name":"Tree Step 1.2",
"id":"2"
}
]
},
{
"name":"Tree Step 2",
"id":"3",
"is_open":true,
"children":[
{
"name":"Tree Step 2.1",
"id":"5"
},
{
"name":"Tree Step 2.2",
"id":"4"
}
]
},
{
"name":"Tree Step 3",
"id":"3",
"is_open":true,
"children":[
{
"name":"Tree Step 3.1",
"id":"5"
},
{
"name":"Tree Step 3.2",
"id":"4"
}
]
}]
}
我需要转换为 HTML 列表,例如:
<ul>
<li>Tree
<ul>
<li>Tree Step 1
<ul>
<li>Tree Step 1.1</li>
<li>Tree Step 1.2</li>
</ul>
</li>
<li>Tree Step 2
<ul>
<li>Tree Step 2.1</li>
<li>Tree Step 2.2</li>
</ul>
</li>
<li>Tree Step 3
<ul>
<li>Tree Step 3.1</li>
<li>Tree Step 3.2</li>
</ul>
</li>
</ul>
</li>
</ul>
我以不同的方式尝试了几次,但无法解决。重要的是要记住,根据用户设置,一个孩子可能有几个孩子。
有没有人做过这样的事情并且可以帮助我?
[编辑(对 Blender 和 Dan Pichelman)] 我使用 PHP 的尝试之一(我没有发布以不溢出问题):
<?php
$dom = new DOMDocument('1.0', 'utf-8');
$dom_menu = $dom->createElement('ul');
$attr = $dom->createAttribute('id');
$attr->value = ('menu');
$dom_menu->appendChild($attr);
$dom->appendChild($dom_menu);
arvore($treeJson, $dom_menu);
function arvore($obj, $dom_pai) {
global $cont;
global $dom;
global $dom_menu;
$id = $obj->name."_".$cont."_".rand(1, 999);
$qtd = count($obj->children);
$uls = childrenPai($obj->children, $dom_menu);
}
function childrenPai($children, $pai) {
global $dom;
for ($i=0; $i<count($children); $i++) {
$ul = $dom->createElement('ul');
$li = criarLi($children[$i], "-");
$ul->appendChild($li);
$pai->appendChild($ul);
$uls[] = $ul;
}
return $uls;
}
function criarLi($obj, $id) {
global $dom;
$e = $dom->createElement('li', $obj->name);
$attr = $dom->createAttribute('id');
$attr->value = $id."_".trim($obj->name);
$e->appendChild($attr);
$dom->appendChild($e);
return $e;
}
echo $dom->saveXML();
那没有正常工作。HTML 列表是用一些“错误”创建的。