0

我在一个 cakephp 项目中工作。实际上我在数据库中有一个表,menu_items其中包含id, parent_id,title和. 我的父菜单项显示正确,但问题出在与.urlis_activeparent_id

foreach($menusitems as $menu) 
{
     if($menu['MenuItem']['is_active'] == true)
     {
          echo $this->Html->link($menu['MenuItem']['title'], array('controller' => 'pages', action' => $menu['MenuItem']['url']));

         foreach ($menu['MenuItem'] as $temp) 
         {
            if($id == $temp['parent_id'])
            {
                echo "match";
            }
        }

     }  

}

这不是一个正确的代码,我只想匹配特定的 id(例如:1)想首先匹配父 id 的每个值,所以我会在哪里找到匹配的值,我将在子菜单列表中打印该值的标题以及具有下一个 ID(例如:2)的相同过程,依此类推。但是我与父 id 匹配的 id 不起作用。

 When i use

'echo "<pre>"
 print_r($menus);
 echo "</pre>"
'
'Array
(
    [id] => 1
    [parent_id] => 
    [title] => Home
    [url] => home
    [is_active] => 1
)

 Array
(
    [id] => 2
    [parent_id] => 
    [title] => Profile
    [url] => 
    [is_active] => 1
)

 Array
(
    [id] => 3
    [parent_id] => 
    [title] => Home
    [url] => home
    [is_active] => 1
)

Array
(
    [id] => 4
    [parent_id] => 2
    [title] => Bussiness Profile
    [url] => bussiness_profile
    [is_active] => 1
)'

我只想将业务显示为 Profile 下的子菜单。如果 id 即 1 等于任何父 id,我正在匹配。如果在我的情况下存在任何父 ID,例如“业务资料”,那么该项目应显示为 Profile 的子菜单。

4

1 回答 1

0

find ('threaded')为您解决问题。$this->MenuItem->find('threaded', array('conditions' => array('MenuItem.is_active')))在您的控制器中使用,应该返回一个看起来像的数组

[0] => array(
    ['MenuItem'] => array(
        [id] => 1
        [parent_id] => 
        [title] => Home
        [url] => home
        [is_active] => 1
     ),
),
[1] => array(
    ['MenuItem'] => array(
        [id] => 2
        [parent_id] => 
        [title] => Profile
        [url] => home
        [is_active] => 1
     ),
     ['children'] => array(
          [MenuItem] => array(
               [id] => 4
               [parent_id] => 2
               [title] => Bussiness Profile
               [url] => bussiness_profile
               [is_active] => 1
          )
     )
 .
 .
)

所以,在你看来:

<ul class="menu">
<?php foreach($menuitems as $menu_item_parent): ?>
     <li class="parent">
         //$this->Html->link .. (with $menu_item_parent)

         <?php if(!empty($menu_item_parent['children'])): ?>
              <ul class="submenu">
              <?php foreach($menuitems['children'] as $menu_item_child): ?>
                    <li class="child">
                          //$this->Html->link .. (with $menu_item_child)
                    </li>
              <?php endforeach; ?>
              </ul>
         <?php endif; ?>
     </li>
<?php endforeach; ?>
</ul>
于 2013-06-24T14:13:23.327 回答