簡體   English   中英

將會話存儲為關聯數組

[英]Store session as associative array

有沒有一種方法可以將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']);

就在這里。 但是我建議您像這樣使用它。 每一個問題是一個數組,什么有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'];

為什么不只將所有答案存儲為單個會話密鑰中的關聯數組?

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

然后,您可以根據需要將每個單獨的請求添加到其中

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

等等等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM