保持第一列的值(即id)并与同一个表php中的另一列(即parent_id)的所有值匹配

时间:2013-06-24 10:35:13

标签: cakephp

我在一个cakephp项目中工作。实际上我在数据库中有表menu_items,其中包含idparent_idtitleurlis_active。我的父菜单项正常显示,但问题出在子菜单中,与parent_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(ex: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,即等于任何父ID,我匹配。如果在我的情况下存在任何父ID,例如“Bussiness Profile”那么该项目应该显示为Profile的子菜单。

1 个答案:

答案 0 :(得分:0)

find ('threaded')为你做了诀窍。 在Controller中使用$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>