Cakephp3如何在控制器中查看和循环获取值

时间:2019-03-05 14:03:47

标签: javascript php cakephp cakephp-3.0

我正在使用cakephp3。实现视图:

enter image description here 在我的takeexam.ctp中:

<table class="table">
  <?php if(!empty($exam->questions)):?>
     <?php foreach ($exam->questions as $questions):?>
        <tr>
           <td colspan="4">
              <?php $x=$x+1; echo $x; ?>.) <?= h($questions->question) ?>
              <input type="hidden" name="b-<?= h($x) ?>" value="<?= h($questions->correct_answer) ?>">
            </td>
        </tr>
        <tr>
            <?php foreach ($questions->answers as $answers):?>
               <?php if($questions->id == $answers->question_id):?>
            <td>
                <span class="choices"><input type="radio" name="a-<?= h($x) ?>"><?= h($answers->answer_text) ?>
                <span>
            </td>
                <?php endif; ?>
            <?php endforeach; ?>
         </tr>
      <?php endforeach; ?>
   <?php endif; ?>
</table>

我想遍历所有问题,获取答案,如果答案正确,则添加分数。问题出在控制器中,当我在变量中使用for循环时。我不能正确执行它,因为cakephp无法读取像$ exam-> a-1这样的变量,因为我在输入名称中使用数字。我该如何正确编写呢?还有其他替代方法吗?

这是我在ExamsController.php中的代码:

public function takeexam($id = null)
{
   $exam = $this->Exams->get($id, [
       'contain' => ['Users', 'Subjects','Questions','Questions.Answers']
     ]);
 if ($this->request->is(['patch', 'post', 'put'])) {
   $exam = $this->Exams->patchEntity($exam, $this->request->getData());
   $total_number = $exam->total_number;
   print_r($exam->a-1);
   for($x=1;$x<=$total_number;$x++){
      if ($exam->a-.$x == $exam->b-.$x){   //here is the error
         //score + 1
      }
    }
  }
  $answers = TableRegistry::get('Questions')->Answers->find('list', 
  ['limit'=>200]);
  $x=0;
  $this->set(compact('question', 'exams','x','answers'));
  $this->set('exam', $exam, 'question');
  $this->set('_serialize', ['exam']);
}

0 个答案:

没有答案