使用http_build_query()通过URL传递关联数组

时间:2018-04-02 12:39:26

标签: php arrays

我有两个页面:page1.php,它包含一个包含表单潜在错误消息的关联数组。

$errors array:

Array ( [password] => password is required. [email] => email is required. )

此数组可能包含更多错误,或者可能包含更少的错误。

我试图通过url将其传递到另一个要显示在相应表单字段旁边的页面。

page1.php:

$a = http_build_query($errors);
header("Location: /test/page2.php?errors=".$a); 
exit();

URL:

http://localhost/test/page2.php?errors=password=password+is+required.&email=email+is+required.

然而,网址似乎没有正确显示,当我检索$ errors数组时,当我被重定向到page2.php时,它不再是一个数组。

page2.php:

if(isset($_GET['errors'])){
$errors = $_GET['errors'];
print_r($errors);
$errors:
password=password is required.

我试图让$errors arraypage1.php上显示的内容完全一样,然后再通过网址发送。

编辑:新网址:

http://localhost/test/page2.php?a=errors%5Bpassword%5D=password+is+required.&errors%5Bemail%5D=email+is+required.

1 个答案:

答案 0 :(得分:2)

您构建的网址错误,以下是一个可以帮助您的网站的示例:

// Just as an example:
$errors = array(
    "password" => "password is required",
    "email" => "email is required"
);

$queries = array(
    "errors" => $errors
);

$queryString = http_build_query($queries);

// This results in the string
// "errors%5Bpassword%5D=password+is+required&errors%5Bemail%5D=email+is+required"
// We simply append this to our header for the full redirect URL:

header("Location: /test/page2.php?".$queryString);

// The full url is then (for example):
// http://localhost/test/page2.php?errors%5Bpassword%5D=password+is+required&errors%5Bemail%5D=email+is+required

您可以像常规GET参数一样在page2.php中获取这些变量:

$errors = $_GET["errors"];