zooandzoo
2012-08-31 13:22:34 +08:00
这种算法常用语无限分类高效查询,树结构左右分值。。。查询简单,难在如何对节点的增、删、改查、移动、赋值
本身就是为了解决递归才用这中算法的,如果在其中用到了递归说明你的思路是错误的~!
<?php
function getList(){
$start=1;
$items = $menu->getItems();
/*
* $items=array(
array(
'title'=>'类别名称',
'deeper'=>false,
'shallower'=>false,
'level_diff'=>0
'level'=>2 //缩进等级
)
); */
$lastitem = 0;
if ($items) {
foreach($items as $i => $item)
{
//初始化
$item['deeper'] = false;
$item['shallower'] = false;
$item['level_diff'] = 0;
if (isset($items[$lastitem])) {
$items[$lastitem]['deeper'] = ($item['level'] > $items[$lastitem]['level']); //该类菜单是否有子菜单
$items[$lastitem]['shallower'] = ($item['level'] < $items[$lastitem]['level']); //是否是该级别的最后一个
$items[$lastitem]['level_diff'] = ($items[$lastitem]['level'] - $item['level']); //级别差用来闭合UL和LI的
}
$lastitem= $i;
}
//用来闭合最顶级ROOT标签
if (isset($items[$lastitem])) {
$items[$lastitem]['deeper'] = (($start?$start:1) > $items[$lastitem]['level']);
$items[$lastitem]['shallower'] = (($start?$start:1) < $items[$lastitem]['level']);
$items[$lastitem]['level_diff'] = ($items[$lastitem]['level'] - ($start?$start:1));
}
}
return $items;
}
?>
<ul>
<?php
$list=getList();
foreach ($list as $i => $item) :
echo '<li>';
echo '<a href="#">'.$item['title'].'</a>';
if ($item->deeper) {
echo '<ul>';
}
elseif ($item->shallower) {
echo '</li>';
echo str_repeat('</ul></li>', $item->level_diff);
}
else {
echo '</li>';
}
endforeach;
?>
</ul>