如何在php中通过$_GET传递数组? [英] How to pass an array via $_GET in php?

查看:24
本文介绍了如何在php中通过$_GET传递数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 $_GET 将一个或多个数组类型的变量传递到另一个页面?

How can I pass one or more variables of type array to another page via $_GET?

我总是以 ?a=1&b=2&c=3

传递 a=[1,2,3] 怎么样?

我是否需要编写一个 for 循环并附加所有值?

Do I need to write a for loop and append all the values?

谢谢

推荐答案

您可以使用 [] 语法通过 _GET 传递数组:

You can use the [] syntax to pass arrays through _GET:

?a[]=1&a[]=2&a[]=3

PHP 理解这种语法,所以 $_GET['a'] 将等于 array(1, 2, 3).

PHP understands this syntax, so $_GET['a'] will be equal to array(1, 2, 3).

您也可以指定键:

?a[42]=1&a[foo]=2&a[bar]=3

多维数组也适用:

?a[42][b][c]=1&a[foo]=2

http_build_query() 会自动执行此操作:

http_build_query() does this automatically:

http_build_query(array('a' => array(1, 2, 3))) // "a[]=1&a[]=2&a[]=3"

http_build_query(array(
    'a' => array(
        'foo' => 'bar',
        'bar' => array(1, 2, 3),
     )
)); // "a[foo]=bar&a[bar][]=1&a[bar][]=2&a[bar][]=3"

<小时>

另一种方法是传递 json 编码的数组:


An alternative would be to pass json encoded arrays:

?a=[1,2,3]

你可以用json_decode解析a:

$a = json_decode($_GET['a']); // array(1, 2, 3)

并用json_encode再次编码:

And encode it again with json_encode:

json_encode(array(1, 2, 3)); // "[1,2,3]"

<小时>

切勿将 serialize() 用于此目的.Serialize 允许序列化对象,并且有一些方法可以让它们执行代码.所以你永远不应该反序列化不受信任的字符串.


Dont ever use serialize() for this purpose. Serialize allows to serialize objects, and there is ways to make them execute code. So you should never deserialize untrusted strings.

这篇关于如何在php中通过$_GET传递数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆