Search code examples
arraysloopscodeigniter

Looped process only shows the first result per iteration


In my CodeIgniter application, I receive a set of student admission number which should be checked in.

Admission numbers are accessed with $ad_no = $this->input->post('adn_no'); and might look like:

array(5) {
    [0]=> string(5) "11784"
    [1]=> string(5) "11837"
    [2]=> string(5) "11775"
    [3]=> string(5) "11937"
    [4]=> string(5) "12061"
}

I attempt to query the database with these numbers, but the result shows only first student result.

My code:

foreach ($ad_no as $key => $id) {
    $this->db->where_in('ad_no', $id);
    $query = $this->db->get('duration');
    $r = $query->result_array();

    $dur = $r[0]['tot_hr'];
    $start = explode(':', $dur);
    $end = explode(':', $tm);
    $total_hours = $start[0] - $end[0];
    $total_hours1 = $start[1] - $end[1];
    $mins = abs($total_hours1);
    $dur = $total_hours . ":" . $mins;
    $durs[$key] = array(
        'ad_no' => $ad_no[$key],
        'tot_hr' => $dur
    );
}
$reslt = $this->Daily_temp_model->duration($durs);

Solution

  • using array push in foreach loop

    $result=[];
    foreach($ad_no as $key => $id) {
        $this->db->where_in('ad_no', $id);
        $query = $this-> db-> get('duration');
        $r = $query-> result_array();
        array_push($result, $r);
        $dur = $r[0]['tot_hr'];
        $start = explode(':', $dur);
        $end = explode(':', $tm);
        $total_hours = $start[0] - $end[0];
        $total_hours1 = $start[1] - $end[1];
        $mins = abs($total_hours1);
        $dur = $total_hours.":".$mins;
        $durs[$key] =
            array(
                'ad_no' => $ad_no[$key],
                'tot_hr' => $dur
            );
    }
    $reslt = $this->Daily_temp_model->duration($durs);