数组的PHP树ul li层次结构菜单 [英] php tree ul li hierarchy menu from array
本文介绍了数组的PHP树ul li层次结构菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们从mysqli查询输出中得到了这个数组:
we have this array from mysqli query output :
$items = Array
(
Array
(
'id' => 1,
'title' => 'menu1',
'parent_id' => 0
),
Array
(
'id' => 2,
'title' => 'submenu1-1',
'parent_id' => 1
),
Array
(
'id' => 3,
'title' => 'submenu1-2',
'parent_id' => 1
),
Array
(
'id' => 4,
'title' => 'menu2',
'parent_id' => 0
),
Array
(
'id' => 5,
'title' => 'submenu2-1',
'parent_id' => 4
)
);
,我们需要将此html输出与php一起使用:
and we need this html output with php :
<ul>
<li><a>menu1</a>
<ul>
<li><a>submenu1-1</a></li>
<li><a>submenu1-2</a></li>
</ul>
</li>
<li><a>menu2</a>
<ul>
<li><a>submenu2-1</a></li>
</ul>
</li>
</ul>
有人可以帮助我吗? 也许这很容易,但是我已经尝试了一切而没有成功!
can anyone help me ? Probably this is very easy but I have tried everything already without success !!
推荐答案
//index elements by id
foreach ($items as $item) {
$item['subs'] = array();
$indexedItems[$item['id']] = (object) $item;
}
//assign to parent
$topLevel = array();
foreach ($indexedItems as $item) {
if ($item->parent_id == 0) {
$topLevel[] = $item;
} else {
$indexedItems[$item->parent_id]->subs[] = $item;
}
}
//recursive function
function renderMenu($items) {
$render = '<ul>';
foreach ($items as $item) {
$render .= '<li>' . $item->title;
if (!empty($item->subs)) {
$render .= renderMenu($item->subs);
}
$render .= '</li>';
}
return $render . '</ul>';
}
echo renderMenu($topLevel);
这篇关于数组的PHP树ul li层次结构菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文