0

I am trying to make a dynamic associtive array but the thing is it just save the last key-value pair how can i store all the key-value pairs?

foreach ($_POST as $var => $value) {



   // Does the model have this attribute? If not raise an error
        if ($model->hasAttribute($var))
            $model->$var = $value;
        elseif ($profile->hasAttribute($var)) {
            $storage = array($var => $value);//associative array
        } else {
            //var_dump ($var);
            $this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']));
        }
    }

2 Answers 2

1

You have only below error:

 $storage = array($var => $value);//associative array

This line is creating a new array $storage every time, that's why you are getting only last key value pair.

Try this:

 $storage = array();// initialize it as array
 $storage[$var] = $value;// assign $value in $key index of $storage 
Sign up to request clarification or add additional context in comments.

Comments

0

In your code, you're always assigning the $storage to a new array instead of appending it.(Correct me if I'm wrong).

You should append the array this way.

 <?php

foreach ($_POST as $var => $value) {

    // Does the model have this attribute? If not raise an error
    if ($model->hasAttribute($var))
        $model->$var = $value;
    else if ($profile->hasAttribute($var)) {
        if (!is_array($storage))
            $storage = [];
        $storage[$var] = $value; //associative array
    } else {
        //var_dump ($var);
        $this->_sendResponse(500, sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var, $_GET['model']));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.