在 Yii2 会话中存储 $_POST [英] Store $_POST in Yii2 session
问题描述
我的测验表格有点问题.我正在使用一个页面来显示用户回答的单个问题,从那里我希望保存问题 ID 和选项 ID(我的表单是多项选择,我设置了选项).
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).
我的 HTML 如下所示:
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
)
这很好,我发现的问题是试图保存下一个问题而不覆盖之前的 [question_id] => [option_id].
Which is fine, the problem I'm finding is trying to save the next question without overwriting the previous [question_id] => [option_id].
我明白为什么下面的代码只是覆盖了现有的 session['question'] 变量.但是我很难将每个问题和答案数组保存到我的变量中.
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.
我尝试了 Yii::$app->session['question'][$i] = $question;
并得到 yii\web\ 重载元素的间接修改会话无效
我也试过 array_push
和 array_merge
来尝试组合前面的问题和选择的选项,但也没有运气.请问我在这里做错了什么?
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?
推荐答案
正确的做法是
$q = $_POST['question'];
Yii::$app->session['question'] = array_merge(Yii::$app->session['question'], [$question]);
这篇关于在 Yii2 会话中存储 $_POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!