您的位置:首页 > 编程语言 > PHP开发

php无限分类 树状菜单经典代码

2015-12-29 16:47 633 查看
<?php
header("content-type:text/html;charset=utf-8");
$conn = mysql_connect('127.0.0.1', 'root', '');
$s    = mysql_select_db("local_df", $conn);
mysql_query("set names utf8");
$sql  = "select * from tree";
$rs   = mysql_query($sql);
$arr  = array();
while ($r    = mysql_fetch_array($rs)) {
$arr[] = $r;
}

$tree = getTree($arr);

print_r($tree);

/**
* 树状结构
* @param type $menus   节点信息和
* @return array
*/
function getTree($menus) {
$id          = $level       = 0;
$menuobjs    = array();
$tree        = array();
$notrootmenu = array();
foreach ($menus as $menu) {
$menuobj        = new stdClass();
$menuobj->menu  = $menu;
$id             = $menu['id'];
$level          = $menu['p_id'];
$menuobj->nodes = array();
$menuobjs[$id]  = $menuobj;
if ($level) {
$notrootmenu[] = $menuobj;
} else {
$tree[] = $menuobj;
}
}

foreach ($notrootmenu as $menuobj) {
$menu                      = $menuobj->menu;
$id                        = $menu['id'];
$level                     = $menu['p_id'];
$menuobjs[$level]->nodes[] = $menuobj;
}
return $tree;
}


结果如下:

Array
(
[0] => stdClass Object
(
[menu] => Array
(
[0] => 1
[id] => 1
[1] => 江西
[name] => 江西
[2] => 0
[p_id] => 0
)

[nodes] => Array
(
[0] => stdClass Object
(
[menu] => Array
(
[0] => 4
[id] => 4
[1] => 赣州
[name] => 赣州
[2] => 1
[p_id] => 1
)

[nodes] => Array
(
[0] => stdClass Object
(
[menu] => Array
(
[0] => 8
[id] => 8
[1] => 信丰
[name] => 信丰
[2] => 4
[p_id] => 4
)

[nodes] => Array
(
)

)

)

)

[1] => stdClass Object
(
[menu] => Array
(
[0] => 5
[id] => 5
[1] => 南昌
[name] => 南昌
[2] => 1
[p_id] => 1
)

[nodes] => Array
(
)

)

)

)

[1] => stdClass Object
(
[menu] => Array
(
[0] => 2
[id] => 2
[1] => 湖南
[name] => 湖南
[2] => 0
[p_id] => 0
)

[nodes] => Array
(
[0] => stdClass Object
(
[menu] => Array
(
[0] => 6
[id] => 6
[1] => 长沙
[name] => 长沙
[2] => 2
[p_id] => 2
)

[nodes] => Array
(
)

)

[1] => stdClass Object
(
[menu] => Array
(
[0] => 7
[id] => 7
[1] => 岳阳
[name] => 岳阳
[2] => 2
[p_id] => 2
)

[nodes] => Array
(
)

)

)

)

[2] => stdClass Object
(
[menu] => Array
(
[0] => 3
[id] => 3
[1] => 浙江
[name] => 浙江
[2] => 0
[p_id] => 0
)

[nodes] => Array
(
)

)

)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: