我正在寻找从 JsTree 插件提供的脚本 server.php 生成的条目中输出有序列表(UL -> Li ...)的最简单方法。
谢谢你的灯
也许它可以帮助你:
SELECT * FROM table ORDER BY level;
你会收到这样的东西:
$a = array(
array('id' => 1, 'parent_id' => 0, 'level' => 0),
array('id' => 2, 'parent_id' => 1, 'level' => 1),
array('id' => 3, 'parent_id' => 1, 'level' => 1),
array('id' => 4, 'parent_id' => 2, 'level' => 2),
array('id' => 5, 'parent_id' => 3, 'level' => 2)
);
准备这个数组:
$prepare = array();
foreach ($a as $record) {
$prepare[$record['id']] = $record;
}
并递归遍历它:
function getTree($array, $id, $level = 0)
{
if ($array[$id]['level'] != $level) {
return;
}
echo '<ul>' . PHP_EOL;
echo '<li>' . $id;
foreach ($array as $data) {
if (($data['parent_id'] === $id)){
getTree($array, $data['id'], $level + 1);
}
}
echo '</li>'. PHP_EOL;
echo '</ul>'. PHP_EOL;
}
getTree($prepare, 1);
它的例子确实返回:
<ul>
<li>1<ul>
<li>2<ul>
<li>4</li>
</ul>
</li>
</ul>
<ul>
<li>3<ul>
<li>5</li>
</ul>
</li>
</ul>
</li>
</ul>