how to get the hierarchical menu from mysql

爱⌒轻易说出口 提交于 2019-12-03 20:41:37
Serty Oan
$stmt = "SELECT id, parent_id FROM table";
$items = Array();
$result = mysql_query($stmt);

while ($line = mysql_fetch_assoc($result)) {
    $items[] = $line;
}

$hierarchy = Array();

foreach($items as $item) {
    $parentID = empty($item['parent_id']) ? 0 : $item['parent_id'];

    if(!isset($hierarchy[$parentID])) {
        $hierarchy[$parentID] = Array();
    }

    $hierarchy[$parentID][] = $item;
}

The root level will be $hierarchy[0]. Keys are items ids and values are all direct children.

DrColossos

Take a look at Nested Sets if you don't mind a little more complex solution. Nested Sets have a very good SELECT performance and I assume that selecting is more important here.

With the help of Nested Sets, complex hierarchical data can be managed in a very fashionable and elegant way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!