无法运行foreach循环

时间:2016-02-26 03:54:14

标签: php codeigniter foreach

我的foreach循环出现问题,它始终显示警告:为foreach()提供的参数无效,你能看看并帮我解决这个问题。 这是我的控制者:

function prod_detail($id_sp){
    $this->load->model('product_model');
    $data['prod_detail'] = $this->product_model->getProdDetailByProdId($id_sp);
    $data['prod_errors'] = $this->product_model->getProdDataError($id_sp);
    $data['error_repairing'] = $this->product_model->getProdDataErrorRepairing($id_sp);
    $data['rows']= $this->membership_model->getUserData();
    $data['main_content'] = 'backend/home/manproduct/prod_detail_view';
    $this->load->view('includes/admin/template', $data);
}

这是我的模特:

function getProdDataError($id_sp){
    $this->db->where('id_sp', $id_sp);
    $this->db->where('status', 0);
    $query = $this->db->get('loi');
    if($query->num_rows()>0){
        foreach ($query->result() as $row){
            $data[]=$row;
        }
        return $data;
    }
}
function getProdDataErrorRepairing($id_sp){
    $this->db->where('id_sp', $id_sp);
    $this->db->where('status', 1);
    $query = $this->db->get('loi');
    if($query->num_rows()>0){
        foreach ($query->result() as $row){
            $data[]=$row;
        }
        return $data;
    }
}

以下是我的观点:

if($ud->status==0){
                echo 'Hoạt động';
            }else if($ud->status==1){
             echo '<b>Lỗi<br><ul></b>';
             foreach ($prod_errors as $err) {
                 echo '<li>'.$err->ten_loi.'</li>';
             }
             echo '</ul>';
         }else if($ud->status==2){
             echo '<b>Đang sửa lỗi<br><ul></b>';
             foreach ($error_repairing as $err) {
                 echo '<li>'.$err->ten_loi.'</li>';
             }
             echo '</ul>';
         }else if($ud->status==3){
             echo 'Chưa lắp đặt';
         }

$ud->status==1时可以,但$ud->status==2时会显示警告消息。顺便说一句,我使用codeigniter开发我的网站,你能帮忙吗?

1 个答案:

答案 0 :(得分:3)

试试这个(在尝试迭代它们之前添加对$ prod_errors / $ error_repairing的检查)

if($ud->status==0)
{
                echo 'Hoạt động';
}else if($ud->status==1)
{
    echo '<b>Lỗi<br><ul></b>';
    // first check $prod_errors exists and is not null before iterating it
    if (isset($prod_errors)) 
    {
        foreach ($prod_errors as $err) 
        {
             echo '<li>'.$err->ten_loi.'</li>';
        }
    }
    else{
        echo "No Data found";
    }
    echo '</ul>';
}else if($ud->status==2)
{
    echo '<b>Đang sửa lỗi<br><ul></b>';
    // first check $error_repairing exists and is not null before iterating it
    if (isset($error_repairing)) 
    {
        foreach ($error_repairing as $err)
        {
             echo '<li>'.$err->ten_loi.'</li>';
        }
    }
    else{
        echo "No Data found";
    }
    echo '</ul>';
}else if($ud->status==3)
{
     echo 'Chưa lắp đặt';
}