我正在尝试实施一个轮询系统,如果用户登陆特定的投票页面并实际回答问题,那么将记录id及其选项。例如,假设该问题的ID为67,并且他们回答了选项2,那么我希望数组看起来像这样:67:2
。日志数组数据将保存在SESSION
变量中,每次用户回答问题时,它都会添加到此数组中。当用户尝试导航到他/她已经回答的民意调查时,它将显示已应答的选项。
我知道我可以使用concatenate和in_array
函数,如果这是一个只有数字的数组,比如"3,2,1,5,6"
但是我怎么能为这种类型的数组做这个呢? ("3:1, 2:2, 1:1")
其中第一个数字是id,第二个数字是选择的选项。如何在连接后使用if (in_array($id))
它会是这样的"3:1"
?
答案 0 :(得分:3)
我想说,你可以这样做:
// Log an answer:
$_SESSION["polls"][$question] = $answer;
这样,它将记录:
{
"polls": {
"question-6": "answer-2",
"question-4": "answer-1"
}
}
所以不会有重复。要检查用户是否已经回答,您可以执行以下操作:
in_array("question-6", array_keys($_SESSION["polls"]))
如果用户回答了问题6,这将为您提供。
PHP脚本
<?php
header("Content-type: text/plain"); session_start();
// Log few questions and answers.
$question = "question-67";
$answer = "answer-2";
$_SESSION["polls"][$question] = $answer;
$question = "question-55";
$answer = "answer-1";
$_SESSION["polls"][$question] = $answer;
$question = "question-42";
$answer = "answer-3";
$_SESSION["polls"][$question] = $answer;
// Let's check if the next question, which will be the same one, has been answered or not.
$question = "question-67";
$answer = "answer-2";
if (in_array($question, array_keys($_SESSION["polls"])))
echo "Question has been answered.";
else
echo "Question not answered.";
?>
我得到的输出为:
Question has been answered.