将数组从一个页面传递到另一个页面

5

我有一个包含一些值的数组,比如说

arr['one'] = "one value here";
arr['two'] = "second value here";
arr['three'] = "third value here";

这些数值在home.php页面中,并且在页面底部重定向到detail.php页面。 现在我想在直接发生时将此数组从home.php传递到detail.php。

我可以使用post和get方法发送多少种方式。如果可能的话,请告诉我如何在detail.php页面接收和打印这些值。

非常感谢每种类型的示例。


我不会在这里使用会话。 - Alexander
1
会话应该用于应用程序范围内所需的信息。将其用于在页面之间传递信息是愚蠢的,可能会导致问题。 - Alexander
会话有什么问题吗,@Alexander? - user1463637
2
@Alexander:我不同意,会话是在多个页面之间保留数据的完美方式,特别是当您想要重定向到脚本以避免重新发布数据或者当您想要重定向到错误页面并将错误消息保存在某个地方(而不是URL数据)时。 - koopajah
@Alexander 是对的。会话应该尽可能地避免,只要没有像推送通知/套接字这样需要维持状态的东西存在[参见REST原则],HTTP就应该保持无状态。如果你只是想闪现消息那还好,但我更倾向于采用异步方式处理问题。 - moonwave99
话虽如此,有时使用会话是有用和必要的。尽管如此,OP的问题似乎不是其中之一,或者没有深入解释。无论如何,在PHP中,口味因人而异。 - Alexander
4个回答

4

最简单的方法是使用会话将数组从一个页面存储到另一个页面:

session_start();
$_SESSION['array_to_save'] = $arr;

更多关于会话的信息: http://php.net/manual/en/function.session-start.php 如果您不想使用会话,可以在您的第一页做出以下更改。
$serialized =htmlspecialchars(serialize($arr));
echo "<input type=\"hidden\" name=\"ArrayData\" value=\"$serialized\"/>";

在另一个中,您可以像这样检索数组数据:

$value = unserialize($_POST['ArrayData']);

解决方案在这里找到:https://stackoverflow.com/a/3638962/1606729

3
如果您不想使用会话,可以将页面包含在其他文件中。 file1.php
<php
    $arr = array();
    $arr['one'] = "one value here";
    $arr['two'] = "second value here";
    $arr['three'] = "third value here";
?>

file2.php

<?php

    include "file1.php";

    print_r($arr);
?>

如果数组是动态创建的,并且您想通过 GET 或 POST 传递它,您应该在服务器端形成 URL 并将用户重定向到 HTTP URL 页面,而不是 PHP 文件。
因此,代码类似于: file1.php
<php
    $arr = array();
    $arr['one'] = "one value here";
    $arr['two'] = "second value here";
    $arr['three'] = "third value here";

    $redirect = "http://yoursite.com/file2.php?".http_build_query($arr);
    header( "Location: $redirect" );

?>

file2.php

<?php

    $params = $_GET;

    print_r($params['one']);
    print_r($params['two']);
    print_r($params['three']);
?>

我认为他的数组是动态构建/填充的。 - koopajah
啊!我明白了。是的,他需要使用会话(sessions)。如果不是这样,可以通过第一个页面内部进行重定向。 - Kartik
1
我知道这篇文章发布已经很久了,但是它确实帮助了我!谢谢@Kartik。 - damien hawks

2

home.php 文件

session_start();
if(!empty($arr)){
    $_SESSION['value'] = $arr;
     redirect_to("../detail.php");
}

detail.php

session_start();                    
if(isset($_SESSION['value'])){                           
    foreach ($_SESSION['value'] as $arr) {
        echo $arr . "<br />";
        unset($_SESSION['value']);
    }
}

0

你也可以通过查询参数传递值。

header('Location: detail.php?' . http_build_query($arr, null, '&'));

你可以像这样在detail.php中获取数组:

// your values are in the $_GET array
echo $_GET['one'];  // echoes "one value here" by your example

请注意,如果您通过GET或POST(隐藏输入字段)传递值,则用户可以轻松更改它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接