GaryDevenay
GaryDevenay

Reputation: 2415

Programmatically Building an Associative Array

I am currently building a questionnaire system which spans over multiple steps (pages). I am using an assoc array which is stored in session to store the submitted answers.

I am having problems getting my head around how I would build this up programmatically.

The array should be as follows

array(STEP => array(ANSWER 1, ANSWER 2, ANSWER 3, etc...));

I have the step as a variable '$step' and the answer array is built up as a separate '$answers' variable.

So basically what I need to be able to build up is the following

array($step => $answers);

Upvotes: 0

Views: 1240

Answers (2)

Paolo
Paolo

Reputation: 2472

$x = array();

$answer = array();
$answer[0]= "A 1";
$answer[1]= "A 2";

$x[$step] = $answer;

Upvotes: 0

WWW
WWW

Reputation: 9860

$_SESSION["answers"][$step] = array($ANSWER1, $ANSWER2, <other answers>);

It'd be up to you to define $step and the $ANSWERn variables, of course. And properly initializing your session, too.

After the questionnaire, you'd just step through your array to extract all the answers:

foreach($_SESSION["answers"] as $step => $answer) {
    // magic happens here
}

(edit: I slightly modified the foreach to give you the $step variable)

Upvotes: 1

Related Questions