mysql建立菜单树的表,PHP / MySQL构建树菜单

I am trying to build an un-oredered list menu tree from my database in PHP and MySQL.

I have an array of page objects I am returning from the db. Each page object has parent_id attribute, which is set to null if it doesn't have a parent. Here's what the page objects look like:

page object

id

title

parent_id

If possible I would like to not do it recursively and only hit the database once, since I am going to be building the menu on almost every request. I want to create a function that I can just pass my array of objects to and it will return the html list.

解决方案

I like @mario's solution, and have improved on it with the prevention of the excess

  • . I would just recommend doing an ORDER BY on your SQL query to get the menu in the order you want (might even recommend a weight/sequence column be added to the schema.

Data setup:

$menu = array( // Presumed to have been coming from a SQL SELECT, populated for demo.

array('id'=>1,'title'=>'Menu 1', 'parent_id'=>null),

array('id'=>2,'title'=>'Sub 1.1', 'parent_id'=>1),

array('id'=>3,'title'=>'Sub 1.2', 'parent_id'=>1),

array('id'=>4,'title'=>'Sub 1.3', 'parent_id'=>1),

array('id'=>5,'title'=>'Menu 2', 'parent_id'=>null),

array('id'=>6,'title'=>'Sub 2.1', 'parent_id'=>5),

array('id'=>7,'title'=>'Sub Sub 2.1.1', 'parent_id'=>6),

array('id'=>8,'title'=>'Sub 2.2', 'parent_id'=>5),

array('id'=>9,'title'=>'Menu 3', 'parent_id'=>null),

);

Handling:

function has_children($rows,$id) {

foreach ($rows as $row) {

if ($row['parent_id'] == $id)

return true;

}

return false;

}

function build_menu($rows,$parent=0)

{

$result = "

  • ";

foreach ($rows as $row)

{

if ($row['parent_id'] == $parent){

$result.= "

{$row['title']}";

if (has_children($rows,$row['id']))

$result.= build_menu($rows,$row['id']);

$result.= "

";

}

}

$result.= "

";

return $result;

}

echo build_menu($menu);

Output:

  • Menu 1
    • Sub 1.1
    • Sub 1.2
    • Sub 1.3
  • Menu 2
    • Sub 2.1
      • Sub Sub 2.1.1
    • Sub 2.2
  • Menu 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值