将会话存储为关联数组

时间:2015-08-19 11:07:05

标签: php arrays session

有没有办法将SESSION名称存储为associative数组?

我有以下会话,点击单选按钮后通过ajax进行设置。

$question = span name wherein question is displaying 
$answer = radio button value
$_SESSION['$question'] = "answer";

然后我想把它转换成下面的,我想保留会话变量名作为键。

$QandA = array (question1 => asnwer1, question2 => asnwer2, question3 => asnwer3 );

如果我喜欢这样做并vardump,它就会变成indexed数组

$QandA = array ($_SESSION['$question']);

不确定要放什么钥匙。

  $QandA = array ("what should be here to get session variable name as key"  => $_SESSION['$question']);

2 个答案:

答案 0 :(得分:2)

是的,有。但我建议你像这样使用它。每个问题都是一个数组,具有questionanswer键的内容。

$_SESSION['question1'] = array(
    'question' => 'The question',
    'answer1' => "the answer"
    'answer2' => "other answer",
    'answer3' => "more answer",
);
$_SESSION['question2'] = array(
    'question' => 'Another question',
    'answer1' => "Answer for the other question."
);

//First question
echo $_SESSION["question1"]['question'];
//Answers for the question
echo $_SESSION["question1"]['answer1'];
echo $_SESSION["question1"]['answer2'];
echo $_SESSION["question1"]['answer3'];

//Second question
echo $_SESSION["question2"]['question'];
//Answer for second question
echo $_SESSION["question2"]['answer1'];

答案 1 :(得分:2)

为什么不将所有答案作为关联数组存储在单个会话密钥中?

$_SESSION['question_answers'] = array(
    $question1 => $answer1,
    $question2 => $answer2,
    // etc etc    
);

然后,您可以根据需要添加每个单独的请求

$_SESSION['question_answers'][$question3] = $answer3;

依此类推。