【问题标题】:how to make a recursive loop for a hierarchal navigation using Php Codeigniter? [closed]如何使用 Php Codeigniter 为分层导航创建递归循环? [关闭]
【发布时间】:2017-02-13 17:04:53
【问题描述】:

这是我的表格,我需要使用 php 显示它吗?

例如。导航表

看起来像这样:

有没有这个的php代码?

谢谢!

【问题讨论】:

  • 你有没有尝试写任何东西?如果是这样,请分享它,我们很乐意提供帮助。您应该考虑使用嵌套树 - github.com/Atlantic18/DoctrineExtensions/blob/master/doc/…。这将为您提供将表格转换为层次结构树的方法。
  • @Meezaan-ud-Din 没有告诉我方法,如果你能在下面回答它的话。谢谢

标签: php arrays codeigniter recursion hierarchy


【解决方案1】:

模型中的代码

public function getHierMenu() {
    $rows = $this->db->get('table_name')->result();

    $depthIndex = array('nav_hier_root','nav_hier_d1','nav_hier_d2','nav_hier_d3','nav_hier_d4');
    $menu = [];
    foreach($rows as $row){
        $depth = $row->nav_hier_depth;

        if($depth > 0)
        $menu[$row->$depthIndex[0]] = [];
        if($depth > 1)
        $menu[$row->$depthIndex[0]][] = $row->$depthIndex[1];
        if($depth > 2)
        $menu[$row->$depthIndex[0]][$row->$depthIndex[1]][] = $row->$depthIndex[2];
        if($depth > 3)
        $menu[$row->$depthIndex[0]][$row->$depthIndex[1]][$row->$depthIndex[2]][] = $row->$depthIndex[3];
        if($depth > 4)
        $menu[$row->$depthIndex[0]][$row->$depthIndex[1]][$row->$depthIndex[2]][$row->$depthIndex[3]][] = $row->$depthIndex[4];
    }

    return $menu;
}

更新

使用此递归函数并传递上一个函数返回的数组 ($menu) 以使用 ulli 打印菜单。

function printMenu($menu) {

    echo '<ul>';
    foreach ($menu as $k => $v) {
        echo '<li>';
        if (!empty($v) && is_array($v)) {
            echo $k;
            printMenu($v);
        } else {
            echo $v;
        }
        echo '</li>';
    }
    echo '</ul>';
}

它已经过测试并且工作正常。

【讨论】:

  • 您好,谢谢,但我得到一个错误`非法字符串偏移'doggie'`在这一行找到:$menu[$row-&gt;$depthIndex[0]][$row-&gt;$depthIndex[1]] = $row-&gt;$depthIndex[2];
  • 请让我检查一下,如果发现任何错误,我会尽快更新我的帖子。
  • 好吧,我不知道为什么这是一个非法的字符串偏移量......
  • 现在用更新的代码再试一次。
  • 没有更多错误,但只显示很少的项目Array ( [Animal] =&gt; Array ( [0] =&gt; doggie [doggie] =&gt; Array ( [0] =&gt; herding [herding] =&gt; Array ( [0] =&gt; collie ) ) ) [Vegetable] =&gt; Array ( [0] =&gt; rutabaga ) [Mineral] =&gt; Array ( [0] =&gt; gypsum ) )
猜你喜欢
  • 2013-10-23
  • 2012-11-18
  • 1970-01-01
  • 2018-07-09
相关资源
最近更新 更多