循环post数组使动态

Loop post array to make dynamic

我想让这段代码更简单、更清晰,我正在制作测验应用程序,所以我有 20 个答案。现在这个问题是,如果我想让它有 50 个答案怎么办。我不想输入 50 个新答案。

代码运行良好,但问题是所有代码都是静态的。我怎样才能简化这个以更有效地添加问题?我使用单选按钮作为输入。这也是主要问题,因为它没有动态。我可以循环这个吗?之前尝试过,但没有达到预期效果

public function resultDisplay(){

        $this->data['checks'] = array(
            'quest1' => $this->input->post('quizId1'),
            'quest2' => $this->input->post('quizId2'),
            'quest3' => $this->input->post('quizId3'),
            'quest4' => $this->input->post('quizId4'),
            'quest5' => $this->input->post('quizId5'),
            'quest6' => $this->input->post('quizId6'),
            'quest7' => $this->input->post('quizId7'),
            'quest8' => $this->input->post('quizId8'),
            'quest9' => $this->input->post('quizId9'),
            'quest10' => $this->input->post('quizId10'),
            'quest11' => $this->input->post('quizId11'),
            'quest12' => $this->input->post('quizId12'),
            'quest13' => $this->input->post('quizId13'),
            'quest14' => $this->input->post('quizId14'),
            'quest15' => $this->input->post('quizId15'),
            'quest16' => $this->input->post('quizId16'),
            'quest17' => $this->input->post('quizId17'),
            'quest18' => $this->input->post('quizId18'),
            'quest19' => $this->input->post('quizId19'),
            'quest20' => $this->input->post('quizId20'),
        );

        $this->load->model('quiz_model');

        $this->data['results'] = $this->quiz_model->getQuestions();

        $this->load->view('templates/header');
        $this->load->view('activity/result_display', $this->data);
        $this->load->view('templates/footer');
    }

我查看页面源图像,这是单选按钮的数组,您可以在突出显示的名称上看到它

这是我的单选按钮,我需要把它做成一个数组吗?以及如何?

    <?php $i = 'A';
        foreach($ans_array AS $array_value): 
    ?>
    <?= $i; ?>.&nbsp; 

    <input type="radio" name="quizId<?= $question->id ?>" value="<?= $array_value ?>" required /> <?= $array_value ?> <br>

    <?php 
        $i++; 
        endforeach; 
    ?>

使用数组会更有效率。你可以这样做:

<input type="radio" name="quizId[<?= $question->id ?>]" value="<?= $array_value ?>" required /> <?= $array_value ?> <br />

因此,在 post 之后,您可以遍历整个循环并获得 post 结果,例如:

foreach($this->input->post('quizId') as $val){
    //work with each value here
} 

我看到你可以这样更新控制器:

$this->data['checks'] = $this->input->post('quizId');

您已将整个数组发送至 view。现在在 view 文件中,您需要将键值指定为 quizId . $key.