codeigniterco

Codeigniter Array Display


I want to display values of an array, but it only displays one value of the array rather than all values of the array.

Model:

function get_subject_position($exam_id , $class_id , $subject_id ) {

        $this->db->where('exam_id' , $exam_id);
        $this->db->where('class_id' , $class_id);
        $this->db->where('subject_id' , $subject_id);
        $this->db->select('mark_obtained');
        $this->db->order_by('mark_obtained DESC');
        $subject_position = $this->db->get('mark')->result_array();
        foreach($subject_position as $row) {

             return $row;     
        }
        }

View:

$subject_pos = $this->crud_model->get_subject_position($row2['exam_id'], $class_id, $row3['subject_id']);

<td style="text-align: center;"><?php echo $subject_pos['mark_obtained'];?></td>

Solution

  • You need to move the "foreach" loop into your view, because right now it's returning the first $row, and then stopping the foreach loop ("return" stops looping)

    Example:

    View

    <?php
    $subject_pos = $this->crud_model->get_subject_position($row2['exam_id'], $class_id, $row3['subject_id']);
    foreach($subject_pos as $row) {
    ?>
    <tr>
        <td style="text-align: center;"><?=$row['mark_obtained']?></td>
    </tr>
    <?php } ?>
    

    Function

    function get_subject_position($exam_id , $class_id , $subject_id ) {
    
        $this->db->where('exam_id' , $exam_id);
        $this->db->where('class_id' , $class_id);
        $this->db->where('subject_id' , $subject_id);
        $this->db->select('mark_obtained');
        $this->db->order_by('mark_obtained DESC');
    
        return $this->db->get('mark')->result_array(); // Get ALL rows
    
        }