php - 计算数据库中正确答案的数量
问题描述
我正在尝试计算数据库中的正确答案。我有以下代码行:
$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);
}
解决方案
将此替换为
$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);
}
推荐阅读
- angular - 如何在角度模板文件中显示base64 pdf
- php - imagecreatefrompng() 生成黑色背景而不是图像中的透明部分
- rollup - 如何将其他捆绑包添加到 Sapper 汇总项目
- java - 单击 ImageButton 后,我想创建一个声音并移动下一个活动
- angular - 如何解决 Uncaught TypeError: Object(...) is not a function?
- typescript - 如何解释 IDB 中 KnownKeys 类型的含义?
- mysql - 在 json 列中保存数字或字符串而无需指定键?这可能吗?
- javascript - 如何在 vue.js 中调用 webassembly 方法?
- python - 填充已经拆分的 numpy 数组
- excel - MS excel VBA:消息框依赖于 Vlookup 结果