drh37116 2017-04-22 10:34
浏览 22
已采纳

在PHP中使用Error错误时出错

I want to do the same actions thru some variables. So I created the variables of variables. But it is throwing me error - "Invalid argument supplied for foreach()" when I am looping thru $$a. I have check the type of the variable. It is array. Then what is the error ?

    $edu_data = Json::decode($model->education);
    $exp_data = Json::decode($model->experience);
    $avail_data = Json::decode($model->availability);
    $docs_data = Json::decode($model->documents);

    $model_edu = new \admin\models\ApplicantEducation();
    $model_exp = new \admin\models\ApplicantExperience();
    $model_avail = new \admin\models\Availability();
    $model_cre = new \admin\models\Credential();

    $all = array('edu_data' => 'model_edu', 'exp_data' => 'model_exp', 'avail_data' => 'model_avail', 'docs_data' => 'model_cre');
    foreach ($all as $a => $s)
    {
        $arr = $$a;
        foreach ($arr as $v)
        {
            $$s->applicant_id = $applicant_id;
            foreach ($arr[1] as $k1 => $v1)
            {
                $$s->$k1 = $v[$k1];
            }
            $$s->save();
        }
    }
  • 写回答

1条回答 默认 最新

  • dongshui9690 2017-04-22 10:36
    关注

    Your array does not contain your variables (e.g. $model_edu), but only their respective names as string values ('model_edu'). Edit: My bad, I didn't notice this is intentional.

    I suggest using a function:

    function process_data($model, $data, $applicant_id) {
        foreach ($data as $v) {
            $model->applicant_id = $applicant_id;
            foreach ($data[1] as $k1 => $v1)
            {
                $model->$k1 = $v[$k1];
            }
            $model->save();
        }
    }
    
    process_data($model_edu, $edu_data);
    process_data($model_exp, $exp_data);
    process_data($model_avail, $avail_data);
    process_data($model_docs, $docs_data);
    

    Your code will be more easily comprehendable.

    Apart from that, you can debug your code like this to find out exactly where and when the error happens:

    foreach ($all as $a => $s)
    {
        $arr = $$a;
    
        var_dump($arr);
    
        foreach ($arr as $v)
        {
            $$s->applicant_id = $applicant_id;
    
            var_dump($arr[1]);
    
            foreach ($arr[1] as $k1 => $v1)
            {
                $$s->$k1 = $v[$k1];
            }
            $$s->save();
        }
    }
    

    See if this is the expected value and proceed from there on.
    Find out if the reason is an unexpected value in one of your variables or if it is an error in the code logic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了