首页 > 解决方案 > 计算数据库中正确答案的数量

问题描述

我正在尝试计算数据库中的正确答案。我有以下代码行:

$getresult = $quizAns->getAnswersByUser($_POST['user_id']); 

if($getresult){

$count = count($getresult);

for ($x = 1; $x <= $count; $x++) {

      $match = $quiz->matchAnswer($getresult[$x]->question_id, $getresult[$x]->ans_id);

  }

}

$counts = count($match);

$getresult我收到用户提交的答案数中,该数必须始终为 4,如下所示:

   Array
(
    [0] => stdClass Object
        (
            [id] => 220
            [user_id] => 84
            [question_id] => 43
            [answer_id] => 31
        )

[1] => stdClass Object
    (
        [id] => 219
        [user_id] => 84
        [question_id] => 48
        [answer_id] => 53
    )

[2] => stdClass Object
    (
        [id] => 218
        [user_id] => 84
        [question_id] => 49
        [answer_id] => 56
    )

[3] => stdClass Object
    (
        [id] => 217
        [user_id] => 84
        [question_id] => 50
        [answer_id] => 62
    )

)

我想遍历每个索引并计算匹配答案的数量。但是,如果我尝试调试,$counts我只会得到 1。我希望有 4 或 3 个,但不仅仅是一个。以下代码用于函数匹配答案:

public function matchAnswer($question_id, $ans_id){

    $args = array(

            'where' => array(

            'id'    => $question_id,
            'ans_id' => $ans_id

        )

    );

    return $this->select($args);

}

这里是函数getAnswersByUser

public function getAnswersByUser($id, $is_die = false){

    $args = array(

        'where' => array(

            'user_id' => $id

            )


        );

        return $this->select($args);

}

标签: phploopsoop

解决方案


将此替换为

$getresult = $quizAns->getAnswersByUser($_POST['user_id']); 

if($getresult){

$count = count($getresult);

for ($x = 1; $x <= $count; $x++) {

  $match = $quiz->matchAnswer($getresult[$x]->question_id,$getresult[$x]->ans_id);

}

}

$counts = count($match);

$getresult = $quizAns->getAnswersByUser($_POST['user_id']); 
$counts = 0;
if($getresult){
    $count = count($getresult);
    for ($x = 0; $x < $count; $x++) {
        $match = $quiz->matchAnswer($getresult[$x]->question_id, $getresult[$x]->ans_id);
        if($match){
           $counts += 1;
        }
    }
}
    $counts = count($match);
} 

推荐阅读