使用多维数组显示结果



我正在研究题库系统,我在显示问题列表和表中的答案方面存在问题。

单击查看表图像

我想这样显示结果:

$question = array{
            array {
                'question' => 'Question MCQ',
                'answer'   => array{
                    'answer 1',
                    'answer 2',
                    'answer 3',
                    'answer 4',
                },
                'correct_answer' = 0
            },
            array {
                'question' => 'Question MCA',
                'answer'   => array{
                    'answer 1',
                    'answer 2',
                    'answer 3',
                    'answer 4',
                },
                'correct_answer' = 2
            },
            array {
                'question' => 'Question True and False',
                'answer'   => array{
                    'True',
                    'False',
                },
                'correct_answer' = 1
            },
}

我现在正在处理的代码是这样的:

  1. getQuestionByID ()

    $select = $this->select()
            ->setIntegrityCheck(false)
            ->from(array('q' => $this->_name), array('questionID', 'questionDesc'));
    $query = $select->query();
    $statement = $query->fetchAll();
    return $statement;
    
  2. getMcQ ()

    $select = $this->select()
            ->setIntegrityCheck(false)
            ->from(array('q' => 'questions'), array('questionID', 'questionDesc'))
            ->join(array('aq' => 'qanswer'), 'q.questionID = aq.questionID')
            ->join(array('a' => 'answers'), 'aq.answerID = a.answerID', array('answerID', 'answerDesc', 'isAnswer'));
    $query = $select->query();
    $stamnt = $query->fetchAll();
    return $stamnt;
    
  3. 控制器
  4. $getQ = new Questions();
    $res = $getQ->getQuestionByID();
    $questions = array();
    foreach ($res as $que) {
        $tmp['question'] = $que->questionDesc;
        $res_ans = $getQ->getMcq();
        $index = 0;
        foreach ($res_ans as $ans) {
            $tmp['answer'] = $ans->answerDesc;
            if ($ans->isAnswer == 1) {
                $tmp['correct_answer'] = $index;
            }
            $index++;
        }
        array_push($questions, $tmp);
    }
    echo "<pre>";
    print_r($questions);
    
  5. 我的代码的结果:点击查看代码

  6. 的结果

有什么帮助吗?提前感谢

我不明白你想用'correct_answer'做什么,但我认为用这个代替你的控制器代码,它应该对你有帮助(除了'correct_answer'字段,但其余的原则是一样的)。

$getQ    = new Questions();
$res     = $getQ->getQuestionByID();
$res_ans = $getQ->getMcq();
$questions = array();
foreach ($res as $que) {
    $tmp = array();
    $tmp['question'] = $que->questionDesc;
    $index = 0;
    foreach ($res_ans as $ans) {
        if ($ans->questionID == $que->questionID){
            $tmp['answer'][] = $ans->answerDesc;
            if ($ans->isAnswer == 1) {
                $tmp['correct_answer'] = $index;
            }
            $index++;
        }
    }
    array_push($questions, $tmp);
}
echo "<pre>";
print_r($questions);
echo "</pre>";

相关内容

  • 没有找到相关文章

最新更新