我在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++)
{
}
答案 0 :(得分:0)
使用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 />";
}
}
}
}
?>