为什么while循环在循环中第一次迭代后没有显示结果?

时间:2016-03-27 06:39:15

标签: php while-loop

我正在尝试通过newsfeed_id获取while循环中的注释,但是在第一次迭代后它没有显示任何结果。我print_r动态生成查询其工作正常,但结果未显示。

    $NewsfeedRes = array();
    $Newsfeed = "select * from `ws_newsfeed` where `nf_status` = 1";
    $NewsfeedQuery = mysqli_query($this->connection,$Newsfeed);
    while($rowNews = mysqli_fetch_assoc($NewsfeedQuery)){
            $NewsfeedRes[] = $rowNews;
            $PushComment = "SELECT cmt.`cmt_id`,cmt.`cmt_comment`,cmt.`date_added`,
                            us.`u_username`,us.`u_image` 
                            FROM `ws_comments` AS cmt 
                            LEFT JOIN `ws_user` AS us ON cmt.`u_id`=us.`u_id` 
                            WHERE cmt.`cmt_target_id` = ".$rowNews['nf_id']." 
                            AND cmt.`cmt_table_name`='ws_newsfeed'";
            //echo $PushComment; This giving me correct query
            $PushCommentQuery = mysqli_query($this->connection,$PushComment);
            while($rowPComment = mysqli_fetch_assoc($PushCommentQuery)){
                $NewsfeedRes['comments'] = $rowPComment;
            }
    }
    $output = array(

        'NewsfeedRes' => $NewsfeedRes,
    );
    echo json_encode($output, JSON_PRETTY_PRINT);

任何人都可以指导我,我可以解决问题。我会很感激。感谢

1 个答案:

答案 0 :(得分:0)

每次循环获取注释循环时,您都会重置$ NewsfeedRes ['comments']的值。你需要将$ rowPComment推入一个数组。

如果你想让$ rowNews和comment在同一个数组中,请尝试:

 while($rowNews = mysqli_fetch_assoc($NewsfeedQuery)){
        $PushComment = "SELECT cmt.`cmt_id`,cmt.`cmt_comment`,cmt.`date_added`,us.`u_username`,us.`u_image` FROM `ws_comments` AS cmt LEFT JOIN `ws_user` AS us ON cmt.`u_id`=us.`u_id` WHERE cmt.`cmt_target_id` = ".$rowNews['nf_id']." AND cmt.`cmt_table_name`='ws_newsfeed'";
        //echo $PushComment; This giving me correct query
        $PushCommentQuery = mysqli_query($this->connection,$PushComment);
        while($rowPComment = mysqli_fetch_assoc($PushCommentQuery)){
            $rowNews['comments'][] = $rowPComment;
        }
        $NewsfeedRes[] = $rowNews;
}

如果你想要一个单独的数组用于评论和新闻提要,请尝试:

    while($rowNews = mysqli_fetch_assoc($NewsfeedQuery)){
        $NewsfeedRes["newsfeed"][] = $rowNews;
        $PushComment = "SELECT cmt.`cmt_id`,cmt.`cmt_comment`,cmt.`date_added`,us.`u_username`,us.`u_image` FROM `ws_comments` AS cmt LEFT JOIN `ws_user` AS us ON cmt.`u_id`=us.`u_id` WHERE cmt.`cmt_target_id` = ".$rowNews['nf_id']." AND cmt.`cmt_table_name`='ws_newsfeed'";
        //echo $PushComment; This giving me correct query
        $PushCommentQuery = mysqli_query($this->connection,$PushComment);
        while($rowPComment = mysqli_fetch_assoc($PushCommentQuery)){
            $NewsfeedRes['comments'][] = $rowPComment;
        }

}