来自mysql的JsTree ul li

时间:2013-02-12 10:26:55

标签: php mysql list jstree

我正在寻找从JsTree插件提供的脚本server.php生成的条目中输出有序列表(UL - > Li ...)的最简单方法。

Screen Shot of JsTree structure in MySql DB

你的灯光

1 个答案:

答案 0 :(得分:3)

可以帮助你:

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>