0

だから私はmenu、id、title、parent_idのテーブルを持っています

メニューの最下位レベル(たとえばid = 50)にいくつかのコンテンツフィールドを添付しました。次に、そのツリーメニューの最上位の親(id = 1)をクリックすると、添付されているコンテンツを表示したいのですが。子メニューに(どれだけ深くてもかまいません)、親をループする必要があると思いますが、このロジックを手伝ってくれませんか?

コントローラー:

    $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?それと?

4

1 に答える 1

2

うーん...再帰

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()...に渡す関数を考慮した新しい関数を作成できます。

PSコードを実行していないので、コードで問題が発生する可能性があります。これは、このシナリオで再帰を有利に使用する方法の単なる例です。

于 2013-02-15T07:56:17.310 に答える