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.

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

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了