普通网友 2012-10-14 08:14
浏览 22
已采纳

PHP排序数组函数

I have a table that consists of comments. Some of them are replies to other comments and have a value set in parent_commentid table. I'm trying to create a function that checks each element in a result set if there is a value in the parent_columnid and if so take the entire element and sort it inside the element with a comment_id that matches the parent_commentid of the current element in the iteration. This is what I've come up with so far.

    function sort_comments($comments){
    $result = array();
    foreach($comments as $comment){
        if(is_null($comment['parent_commentid'])) $result[] = $comment;
        else{
            $parent_comment = array_search($comment['parent_commentid'], $comments);
            if($parent_array !== false) $result[$parent_comment][] = $comment;
        }
    }
}

array_search is not the function I'm looking for but is the closets thing I could think of. Im not sure where to go from here. Keep in mind also that there can exist replies to other replies.

  • 写回答

2条回答 默认 最新

  • dougekui1518 2012-10-14 08:24
    关注

    You need to store the comments by their own id, so that you can reference them later:

    function sort_comments($comments){
        $result = array();
        foreach($comments as $comment){
            if(is_null($comment['parent_commentid'])){ 
                $result[$comment['commentid']] = $comment;
            }else{
                $parent_comment = $result[$comment['parent_commentid']]
                if($parent_comment) 
                    $parent_comment[$comment['commentid']] = $comment;
                else
                    // what happens in this case:
                    // parent_commentid set, but no such comment exists?
            }
        }
    

    Note the $comment['commentid']. I don't know how you call the id of a comment (commentid ?), but since you have a column parent_commandid you most likely do have such a column to reference your comments. Use that to store the comments, on top level or inside other comments.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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