【问题标题】:Codeigniter: Array returns only one row in viewCodeigniter:数组在视图中仅返回一行
【发布时间】:2017-05-01 03:34:21
【问题描述】:

我正在使用 codeigniter 和 postgresql 在 php 中创建一个考试报告,它显示问题和正确回答问题的学生人数以及错误回答问题的学生人数。当我尝试显示数据时,它只打印一行,而实际上我有 3 行。我使用 print_r() 来知道我的数组的元素是什么,它看起来像这样: RESULT: print_r()

但是当我尝试在视图中显示它时,结果是这样的: Result of displaying in View

我的控制器中有这些:

public function loadViewExamResult(){
    $this->load->model('exam_model');
    $exam_no= $this->uri->segment(3);
    $data['answers'] = $this->exam_model->correctWrong($exam_no);
    print_r($data['answers']) ;

    $this->load->view('exam_report_chart',$data);

}

型号:

 <?php 
    foreach ($answers as $row) {
      $question = $row->question;
      $correct = $row->correct;
      $wrong = $row->wrong;
    }
 ?>


 <div class="row">
   <div class="col-lg-12">
    <section class="panel">
     <header class="panel-heading">
         EXAM STATISTICS
     </header>
     <div class="panel-body text-center">
      <table class="table table-striped table-advance table-hover">
        <tbody>
         <tr>
          <th>QUESTION</th>
          <th>No. of Correct</th>
          <th>No. of Wrong</th>
         </tr>

         <tr>
          <td><?php echo $question;?></td>      
          <td><?php echo $correct;?></td>
          td><?php echo $wrong;?></td>
         </tr>

       </tbody>
      </table>
     </div>
    </section>
   </div>
  </div>

我该如何解决这个问题?

【问题讨论】:

    标签: php arrays codeigniter


    【解决方案1】:

    问题就在这里:

    foreach ($answers as $row) {
          $question = $row->question;
          $correct = $row->correct;
          $wrong = $row->wrong;
    }
    

    在每次迭代中,$question$correct$wrong 中的最后一个值都会被覆盖。使它们成为数组,以便它们可以保存多个值,例如:

    foreach ($answers as $row) {
          $question[] = $row->question;
          $correct[] = $row->correct;
          $wrong[] = $row->wrong;
    }
    

    或将表格 tr 放入循环中,例如:

    foreach ($answers as $row) {
    ?>
    <tr>
      <td><?php echo $row->$question;?></td>      
      <td><?php echo $row->$correct;?></td>
      td><?php echo $row->$wrong;?></td>
    </tr>
    <?php
    }
    ?>
    

    【讨论】:

    • 听起来不错!!
    猜你喜欢
    • 2013-07-04
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多