PHP - 使用$ _SESSION [duplicate]将值从一个页面传递到另一个页面的数组

问题描述 投票:0回答:1

目标:我想传递一个数组,其中包含从页面到另一个页面的值。

问题:说到第二页,我试图print_r数组,它没有任何值。它在第二页上给了我这个php通知:

注意:未定义的索引:第17行的Questionnaire_Category_2.php中的答案

这是我的第一页的代码段,即Questionnaire_Category_1.php

if(isset($_POST['Choice'])){ //When the user submits the answer
    $Answer[] = $_POST['Choice']; //All answers from the form will be placed in the array
    session_start();
    $_SESSION['answers'] = $Answer; //All values of the array will be assigned to the session variable 'answers'
    header("Location: Questionnaire_Category_2.php");
}

这是名为Questionnaire_Category_2.php的第二页的代码段

$ANSWER[] = $_SESSION['answers']; //Get all the values from the session and store it in array and also this is the Line 17 that causes a notice message
echo "<pre>"; print_r($ANSWER); echo "</pre>";

问题:

  1. 我的两个页面的实现是对的吗?
  2. 如果没有,我如何正确地将数组及其值从一个页面传递到另一个页面?
  3. 除了使用$ _SESSION之外还有其他方法吗?
php arrays session session-variables
1个回答
0
投票

在会话中添加和获取值之前执行session_start()

session_start();
$_SESSION['answers'] = $ANSWER;

session_start();
$ANSWER = $_SESSION['answers'];
© www.soinside.com 2019 - 2024. All rights reserved.