我正在尝试实现一个轮询系统,如果用户登陆特定的轮询页面并实际回答了问题,那么 id 和他们的选项将被记录。例如,假设该问题的 id 是 67 并且他们回答了选项 2,那么我希望数组看起来像这样:67:2
。日志数组数据将保存在 SESSION
变量中,每次用户回答问题时,它都会添加到该数组中。当用户尝试导航到他/她已经回答的民意调查时,它将显示已回答的选项。
我知道如果这是一个仅由数字组成的数组,例如“3,2,1,5,6”,我可以使用连接和 in_array 函数,但是如何我可以对这种类型的数组执行此操作吗? ("3:1, 2:2, 1:1")
其中第一个数字是 id,第二个数字是所选的选项。当连接后它会像这样的 "3:1"
时,如何使用 if (in_array($id))
?
最佳答案
我想说,你可以这样做:
// 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.
关于php - 跟踪 2 个键数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41412352/