【问题标题】:Getting php array from one page to another?将php数组从一个页面获取到另一个页面?
【发布时间】:2015-08-10 21:35:23
【问题描述】:

PHP - How to send an array to another page?之前我环顾四周,但我的情况不同。

我在页面上有这个程序,这是查询块:

while ($row = sqlsrv_fetch_array($query))
{   
    $questions[] = "$row[Question]";
    $optionA[] = "$row[OptionA]";
    $optionB[] = "$row[OptionB]";
    $optionC[] = "$row[OptionC]";
    $optionD[] = "$row[OptionD]";
}

然后我做这样的事情来在屏幕上回显问题

$lengthquestion = count($questions);
$_SESSION['length'] = $lengthquestion;
for($i = 0; $i < $lengthquestion; $i++)
{
    echo $questions[$i];
}

现在我希望能够在不同的 php 文件中访问这个问题数组。但是我对我一直在尝试的东西感到困惑/卡住的地方是我仍然需要访问下一页上数组的每个元素。我该怎么办?

到目前为止,我一直在玩会话,但后来出现数组到字符串转换错误。

第二个php页面:

$UpperLimit = $_SESSION['length']; 
for($i = 0; $i < $UpperLimit; $i++)
{

}

【问题讨论】:

  • 既然您已经在使用会话,为什么不将$questions 和选项数组添加到会话中?
  • 每次 $i 都可以不同。这是我尝试过但没有奏效的方法。所以也许我做错了。在我的第一页中,我有 $_SESSION['Questions'] = $questions;在我的第二页中,我有 $QUEST = $_SESSION['Questions'];
  • 我在这里看不到大局,您可以再次运行查询。
  • 是的,但那是我最后的手段。我运行的只是查询取决于不同的变量。所以,如果我不能做到这一点,那么我将运行查询。
  • 为了将数组放入会话中,您需要serialize() 它,然后在要使用该数组的其他脚本中unserialize() 它。

标签: php arrays sql-server


【解决方案1】:

使用 Sessions 将数组发布到另一个页面很容易,但我也建议使用多维数组。

示例(测试代码):

<?php
session_start();
$i = 0;
$questions = Array();

for($i = 0; $i < 5; $i++){
    $questions[$i]['question'] = "test  ". $i;
    $questions[$i]['option'][] = "optionA ". $i;
    $questions[$i]['option'][] = "optionB ". $i;
    $questions[$i]['option'][] = "optionC ". $i;
    $questions[$i]['option'][] = "optionD ". $i;
}

$_SESSION['questions'] = $questions;

// ******* from here down can go on another page.  Don't forget session_start();

$questions_session = $_SESSION['questions'];

if(is_array($questions_session)){
    foreach($questions_session as $key => $questions){
        foreach($questions as $q => $question){
            if(is_array($question)){
                // This is an option, loop through and post each option.
                foreach($question as $key => $option){
                   echo " - ".$option."<br />";
                }
            } else {
                // This is the question, post it to the screen
                echo "Question : ". $question . "<br />";
            }
        }
    }
}
?>

【讨论】:

  • 这不起作用。但是这个问题已经解决了。对于未来的人,我使用了序列化和反序列化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
相关资源
最近更新 更多