如果变量在foreach循环中为真

时间:2013-08-23 11:20:45

标签: php database codeigniter foreach

基本上我有这样的foreach循环:

foreach($_POST['id'] as $key => $id) {
    $qty = $_POST['qty'][$key];
    $bin_location = $_POST['bin_location'][$key];
    $pdi_required = $_POST['pdi_required'.$key][0];
    $pdi_completed = $_POST['pdi_completed'][$key];
    $serial_no = $_POST['serial_no'][$key];
    $movement_by = $_POST['movement_by'][$key];
    $date_moving = $_POST['date_of_movement'][$key];
    $special_instructions = $_POST['special_instructions_admin'][$key];
    $status = strtolower($_POST['status'][$key]);

    $sql_update = "UPDATE products SET status='$status' WHERE job_id='$id'";

    $this->db->query($sql_update);
}

if ($status == 'rejected') {
    $sql_job_update = "UPDATE jobs SET status='rejected' WHERE job_id='$id'";
} elseif ($status =='pending' || $status =='returning') {
    $sql_job_update = "UPDATE jobs SET status='pending' WHERE job_id='$id'";
} else {
    $sql_job_update = "UPDATE jobs SET status='approved'";
}

然而,我这是我最感兴趣的最后一部分(if ($status == whatever)。如何从foreach中获得最低的值?

这是因为我有两个表,jobs有一个已完成的作业表,products是作业中请求的产品。如果产品因任何原因而被拒绝,则整个工作都是失败的,因此该工作应该具有被拒绝的状态。如果它没有被拒绝并且只是待处理,请将其作为待处理。如果接受所有字段,则将作业状态设置为已接受。

我真正需要的是在foreach循环的任何一个事件中获得某个状态是否为真,如果是,则将状态设置为该值。

2 个答案:

答案 0 :(得分:1)

使用在循环之前设置为false的单独变量。在循环内部,如果你具有某种特定状态,则将其设置为true。

编辑:或者,因为您似乎需要考虑两个以上的可能状态值,所以最初将其设置为“已批准”,并使用比较函数来告诉您哪两个状态值较低。然后,在循环中,使用该函数将全局状态设置为自身的最小值和当前循环迭代的状态。

答案 1 :(得分:1)

使用第二个变量

跟踪作业是否失败
$jobStatus = 0;
foreach($_POST['id'] as $key => $id)
{
    $qty = $_POST['qty'][$key];
    $bin_location = $_POST['bin_location'][$key];
    $pdi_required = $_POST['pdi_required'.$key][0];
    $pdi_completed = $_POST['pdi_completed'][$key];
    $serial_no = $_POST['serial_no'][$key];
    $movement_by = $_POST['movement_by'][$key];
    $date_moving = $_POST['date_of_movement'][$key];
    $special_instructions = $_POST['special_instructions_admin'][$key];
    $status = strtolower($_POST['status'][$key]);

    //If any of the statuses are rejected then set
    //the job as failed, otherwise it will stay as FALSE
    if( $status == "rejected") {
        $jobStatus = 1;
    } else if( ($status == "pending" || $status == "returning") && $jobStatus != 1) {
        $jobStatus = 2;
    }

    $sql_update = "UPDATE products SET status='$status' WHERE job_id='$id'";

    $this->db->query($sql_update);
}
if ($jobStatus == 1) {
      $sql_job_update = "UPDATE jobs SET status='rejected' WHERE job_id='$id'";
} elseif ($jobStatus == 2){
      $sql_job_update = "UPDATE jobs SET status='pending' WHERE job_id='$id'";
} else {
      $sql_job_update = "UPDATE jobs SET status='approved'";
}