我在将可变数据存储在数组中然后将数组存储到会话时遇到问题。只有一次该值存储在0索引的数组中,但是当下一个页面加载到下一个按钮时,单击以加载下一个测试,将覆盖数组的值。
<?php session_start();
$cat_name = $_POST["cat_name"];
$which_test_id = $_POST["which_test_id"];
echo $correct = $_POST["correct"];
$answers[] = array('correct' => $correct);
$_SESSION["results"] = $answers;
print_r($_SESSION["results"]); ?>
答案 0 :(得分:2)
在设定之前得到答案:)
<?php session_start();
$cat_name = $_POST["cat_name"];
$which_test_id = $_POST["which_test_id"];
echo $correct = $_POST["correct"];
$answers = (array_key_exists("results", $_SESSION)) ? $_SESSION["results"] : array();
$answers[] = array('correct' => $correct);
$_SESSION["results"] = $answers;
print_r($_SESSION["results"]);
?>
答案 1 :(得分:0)
如果提交,则显示值
.closed-box
答案 2 :(得分:0)
1.您不需要&#34; []&#34;同时声明一个数组。
2.数据被覆盖,因为您没有检查数据是否首先设置。
<?php
ini_set('session.cookie_domain',"localhost");
session_start();
if(isset($_POST['submit']))
{
$cat_name = $_POST["cat_name"];
$which_test_id = $_POST["which_test_id"];
echo $correct = $_POST["correct"];
$answers = array('correct' => $correct);
if(!isset($_SESSION["results"]))
{
$_SESSION["results"] = $answers;
}
}
print_r($_SESSION["results"]); ?>