dsfds2343 2014-04-02 19:06
浏览 43
已采纳

我需要一个节点作为Array中的节点和叶子,具有未定义的深度

I'm working on a comment system, in which one is able to reply to another comment, making it appear below the commented comment. I have a bunch of parent/child pairs, to which end I use recursion to convert this into a tree structure:

private function _create_tree_from_comments($comment_id, $entry_id) {
    $node_set = array();
    $children = $this->comment_model->get_children($comment_id, $entry_id);

    // check if we're a leaf
    if($children->num_rows() < 1) {
        return $comment_id;
    }


    foreach($children->result() as $child) {
        $node_set[$child->child] = $this->_create_tree_from_comments($child->child, $entry_id);
    }

    return $node_set;
}

Now this is all fine and well, but the problem is that I need to save information about intermediate nodes. Currently all I can do is save whatever information I need in another array at a leaf, since the intermediate nodes have responsibility to keep information about their children.

So my question is really: How am I able to save information about intermediate nodes without breaking the relationship there is between the parent and its children.

Some sample output of the function:

Array 
(
     [5] => 5
     [2] => 2
     [1] => Array
         (
               [4] => Array
                   (
                       [6] => 6
                   )

               [3] => 3
         )

)    
  • 写回答

1条回答 默认 最新

  • douzuanze0486 2014-04-02 19:18
    关注

    Each node in your tree could be an array like:

    Array (
         ['comment_id'] => 7
         ['children'] => Array (...)
         ['whatever_else'] => 'foo'
    )
    

    So your function - instead of returning a comment ID or an array - would always return an array that contains possibly a comment id, children or empty array if no children, and anything else you wish to store

    private function _create_tree_from_comments($comment_id, $entry_id) {
        $node_set = array();
    
        $children = $this->comment_model->get_children($comment_id, $entry_id);
    
        // check if we're a leaf
        if($children->num_rows() < 1) {
            $node_set['comment_id'] = $comment_id;
        }
    
        $node_set['children'] = array();
        foreach($children->result() as $child) {
            $node_set['children'][] = $this->_create_tree_from_comments($child->child, $entry_id);
        }
    
        $node_set['whatever_else'] = 'foo';
    
        return $node_set;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大