Store $_POST in Yii2 session

断了今生、忘了曾经 提交于 2019-12-11 02:11:49

问题


I'm having a little trouble with my quiz form. I'm using a page to show a single question that a user answers, from there I was hoping to save the question id and option id (My form is multiple choice, i set the options).

My HTML looks like this:

<input type="radio" name="question[3]" value="4">My Answer

When the form is posted I am doing this

if(isset(Yii::$app->session['question'])){

                // Get posted array
                $question = $_POST['question'];
                Yii::$app->session['question'] = $question;
                print_r(Yii::$app->session['question']);
            }

So it's saved into my session as:

Array
(
[3] => 4
)

Which is fine, the problem I'm finding is trying to save the next question without overwriting the previous [question_id] => [option_id].

I understand why the following code just overwrites the existing the session['question'] variable. But I'm struggling to be able to save each question and answer array to my variable.

I have tried Yii::$app->session['question'][$i] = $question; and get Indirect modification of overloaded element of yii\web\Session has no effect

I've also tried array_push and array_merge to try and combine the previous array of question and chosen option, but have had no luck either. What am I doing wrong here please?


回答1:


The correct way to do this is

$q = $_POST['question'];
Yii::$app->session['question'] = array_merge(Yii::$app->session['question'], [$question]);



回答2:


You should do

Yii::$app->session['question'][] = $question;

Notice the extra []



来源:https://stackoverflow.com/questions/26169991/store-post-in-yii2-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!