在 php 代码点火器中显示嵌套的 foreach 和 if else


Displaying the nested foreach with if else in php codeigniter

Controller

public function admin()
{
    // get the current date employee logged in details
    $data['get_attendance'] = $this->attendance_model->get_attendance();
    // get the active employee details
    $data['get_employee'] = $this->attendance_model->get_employee();
    //print_r($data['get_employee']); exit();
    // attendance page
    $data['header'] = "Employee";
    $data['sub_header'] = "Attendance employee";
    $data['main_content'] = 'attendance/admin_list';
    $this->load->view('employeelayout/main',$data);
}

public function get_attendance()
{
    return $this->db->where('date',date('Y-m-d'))->get('attendance')->result_array();
}
public function get_employee()
{
    return $this->db->where('is_active',1)->get('employee')->result_array();
}

视图

<?php $count = 1 ?>
<?php foreach ($get_employee as $employee) { ?>
<tr class="gradeX">
    <td><?php echo $count++ ?></td>
    <td><?php echo $employee['first_name'] . ' ' . $employee['last_name'] ?></td>
    <td><?php echo $employee['employee_number'] ?></td>
       <?php foreach ($get_attendance as $attendance) : ?>
        <!-- if employee exists -->
           <?php if($employee['employee_id'] == $attendance['employee_id'] ) { ?>
            <td><?php echo date('M-Dj-Y',strtotime($attendance['date'])) ?></td>
            <td><?php echo $attendance['mark_in_time'] ?></td>
               <td>mark out going</td>
               <td>Active</td> 
            <?php  break; ?>
       <?php } elseif($employee['employee_id'] != $attendance['employee_id'] ) { ?>
           <td><?php echo "i'm absent" ?></td>
           <?php  break; ?>
      <?php  } ?>
       <?php endforeach; ?> 
    </tr> 
    <?php } ?>

我想显示当前登录(当前)的员工,并显示缺席的员工。我正在从员工表中获取员工详细信息。以及出勤表中的出勤详细信息。如果员工缺席,而我想显示缺席,则显示登录详细信息。此处 foreach 循环未正确显示 if 条件。循环有什么问题。

试试这个:

<?php foreach ($get_employee as $employee) : ?>
    <tr class="gradeX">
        <td><?php echo $count++ ?></td>
        <td><?php echo $employee['first_name'] . ' ' . $employee['last_name'] ?></td>
        <td><?php echo $employee['employee_number'] ?></td>
           <?php foreach ($get_attendance as $attendance) : ?>
            <!-- if employee exists -->
             <?php if($employee['employee_id'] == $attendance['employee_id']) : ?>
                <td><?php echo date('M-Dj-Y',strtotime($attendance['date'])) ?></td>
                <td><?php echo $attendance['mark_in_time'] ?></td>
                   <td>mark out going</td>
                   <td>Active</td>
             <?php elseif ($employee['employee_id'] != $attendance['employee_id']) : ?>
               <td><?php echo "i'm absent" ?></td>
             <?php else : ?>
             <?php endif; ?>
          <?php endforeach; ?> 
    </tr> 
<?php endforeach; ?>

应用左联接代替两个不同的查询。

因为目前你已经应用了两个循环和它们的比较,会消耗大量的执行时间,而且我不认为这是好的代码,如果你得到数千个数据,你肯定可以分析执行时间。

因此,最好应用联接查询。