显示数据库的所有评论答案

时间:2017-09-18 17:14:06

标签: php sql

通过使用我写的这个模型,我只能从数据库中获得每个评论的答案。

现在我想展示评论的所有答案我该怎么办?

发布模型

<?php

class Model_post extends Model
{
    function postComment($url)
    {
        $sql = "select * from tbl_postcomment where posttitle=? and parent=0";
        $result = $this->doSelect($sql, [$url]);
        $sql = "select * from tbl_postcomment where parent!=0";
        $all_answers = $this->doSelect($sql);
        $all_answer_new = [];
        foreach ($all_answers as $answer) {
            $question_id = $answer['parent'];
            $all_answer_new[$question_id] = $answer;
        }
        return [$result, $all_answer_new];
    }
}

?>

帖子控制器

<?php

class Post extends Controller
{
   function id($url)
    {
        $postComment = $this->model->postComment($url);
        $qestions=$postComment[0];
        $answers=$postComment[1];
        $data = [$qestions,$answers];
        $this->view('post/index', $data);
    }
}

?>

1 个答案:

答案 0 :(得分:0)

$question_id在循环中的问题答案中具有相同的值。您的代码会覆盖以前的答案。而且每个问题只能看到一个答案是正常的。

尝试将答案追加到$all_answer_new[$question_id](这是一个数组。$all_answer_new是一个二维数组,包含所有问题的所有答案。)

$all_answer_new[$question_id] = $answer;替换为以下内容:

if (empty($all_answer_new[$question_id])) {
  $all_answer_new[$question_id] = array();
}
$all_answer_new[$question_id][] = $answer;