php - 列出所有子菜单中的项目(SQL)

标签 php mysql codeigniter

所以我有一个包含菜单、id、标题、parent_id 的表格

我已将一些内容字段附加到菜单的最底层(假设 id = 50),那么如果我单击该树形菜单的顶部父级(id = 1)怎么办,我希望它显示内容附加到子菜单(无论多深),所以我想我需要循环父菜单,你能帮我解决这个逻辑吗?

Controller :

    $data['query'] = $this->item_model->getByType($menu_id);

模型:

function getByType($menu_id) {
    if($menu_id) {
        $q = $this->db->get_where('menus', array('id' => $menu_id));
        $parent_id = $q->row()->parent_id;
    }else{
        return;
    }
    $this->db->select('*');
    $this->db->from('items');
    $this->db->where('menu_id', $menu_id);
    $this->db->or_where('menu_id', $parent_id);
    $query = $this->db->get();
    return $query;
}

所以现在我只能在点击他的父级(2级)时获得某些菜单的项目,但是如何使其无限深?,我想这里我需要放入一个循环or_where,你能帮我吗?

最佳答案

Hmz... Recursion !

function getChildrenAttachments($menu_id) {
    // invalid menu id
    if(!$menu_id) return;
    // get all rows with this parent id
    $query = $this->db->get_where('menus', array('parent_id' => $menu_id));
    // result will hold all the attachments
    $result = array();
    // loop through results
    foreach($query->result() as $row) {
        // does this row have an attachment?
        if($row->attachment!='') {
            $result[] = $row->attachment;
        }
        // add all children attachments
        $result = array_merge($result, getChildrenAttachments($row->id));
    }
    // return result set
    return $result
}

此实现并未考虑当前实际具有附件的 menu_id。您可以创建一个新函数,将 getAttachmentsForTree() 考虑在内,该函数检查当前 id,然后将 id 传递给 getChildrenAttachments()...

附注我还没有运行该代码,因此对于代码可能出现的任何问题,我深表歉意。这只是一个示例,说明如何在这种情况下使用递归来发挥自己的优势。

关于php - 列出所有子菜单中的项目(SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14890094/

相关文章:

php - SQL 数据库中可变列数

php - 导致 fatal error : Call to undefined function mysqli_report()? 的原因

php - 在一个php脚本中将数据插入到两个表中

php - 在 Codeigniter 或其他 MVC 中处理不正确的方法( Controller )参数

php - Blade 模板引擎可以与codeigniter一起使用吗?

php - 通过用户代理识别手机

php - Get - Request ,在 Alert() 中显示结果

创建 View 时mysql union all

php - 使用 MySQL 的 Android 登录页面

php - Composer 类加载器命名空间问题