以编程方式构建关联数组

发布于 2024-12-14 14:32:18 字数 323 浏览 0 评论 0原文

我目前正在构建一个跨越多个步骤(页面)的调查问卷系统。我正在使用存储在会话中的关联数组来存储提交的答案。

我无法理解如何以编程方式构建它。

该数组应如下所示,

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

我将步骤作为变量“$step”,并将答案数组构建为单独的“$answers”变量。

所以基本上我需要能够建立的是以下内容

array($step => $answers);

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

同尘 2024-12-21 14:32:18
$_SESSION["answers"][$step] = array($ANSWER1, $ANSWER2, <other answers>);

当然,您可以定义 $step$ANSWERn 变量。并正确初始化您的会话。

完成调查问卷后,您只需单步遍历数组即可提取所有答案:(

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

编辑:我稍微修改了 foreach 来为您提供 $step 变量)

$_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)

庆幸我还是我 2024-12-21 14:32:18
$x = array();

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

$x[$step] = $answer;
$x = array();

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

$x[$step] = $answer;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文