Is there a way to store SESSION
name as associative
array?
I have this session below, that being set via ajax
once radio button is click.
$question = span name wherein question is displaying
$answer = radio button value
$_SESSION['$question'] = "answer";
Then I want to convert it into below, I want to retain session variable name as key.
$QandA = array (question1 => asnwer1, question2 => asnwer2, question3 => asnwer3 );
If I do like this and do vardump
, it is becoming indexed
array
$QandA = array ($_SESSION['$question']);
Not sure what to put as key.
$QandA = array ("what should be here to get session variable name as key" => $_SESSION['$question']);
Yes, there is. But I recommend you to use it like this. Every question is an array, what has a question
and answer
key.
$_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'];
Why not just store all the answers as an associated array within a single session key?
$_SESSION['question_answers'] = array(
$question1 => $answer1,
$question2 => $answer2,
// etc etc
);
You could then just add to it with every separate request, if necessary
$_SESSION['question_answers'][$question3] = $answer3;
And so on and so forth.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.