是否可以使用knpmenu bundle为symfony2创建多级菜单,而不知道会有多少级别。如果有2级最大值
,则foreach
以下是好的
class MenuRepository
public function getMenuItems()
{
return $this->findBy(array('active' => '1'), array('parent' => 'ASC', 'order' => 'ASC'));
}
}
class Builder extends ContainerAware
{
$menuItems = $em->getRepository('AcmeBundle:Menu')->getMenuItems();
foreach ($menuItems as $key => $item) {
if ($item->getParent() == null) {
$menu->addChild($item->getId(),
array(
'route' => $item->getRoute().'_display',
'label' => $item->getTitle(),
'routeParameters' => array('slug' => $item->getParametry())));
} else {
if (isset($menu[$item->getParent()->getId()] )) {
$menu[$item->getParent()->getId()]->addChild($item->getId(), array(
'route' => $item->getRoute().'_display',
'label' => $item->getTitle(),
'routeParameters' => array('slug' => $item->getParam())));
}
}
}
insertChild
function insertChild($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle->getParent()->getId()===$key ||
($this->insertChild($needle ,$value->getChildren()) !== false)) {
$haystack[$key]->addChild($needle->getId(),
array(
'route' => $needle->getRoute().'_display',
'label' => $needle->getTitle(),
'routeParameters' => array('slug' => $needle->getParam())
));
return $haystack[$key];
}
}
return false;
}