Ish
Ish

Reputation: 2105

Error while using Error of error in PHP

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();
        }
    }

Upvotes: 0

Views: 53

Answers (1)

Imanuel
Imanuel

Reputation: 3667

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.

Upvotes: 3

Related Questions