将数组作为 url 参数传递 [英] Passing arrays as url parameter

查看:46
本文介绍了将数组作为 url 参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将数组作为 url 参数传递的最佳方式是什么?我在想这是否可能:

What is the best way that I can pass an array as a url parameter? I was thinking if this is possible:

$aValues = array();

$url = 'http://www.example.com?aParam='.$aValues;

或者这个怎​​么样:

$url = 'http://www.example.com?aParam[]='.$aValues;

我读过例子,但我觉得它很乱:

Ive read examples, but I find it messy:

$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';

推荐答案

有一个非常简单的解决方案:http_build_query().它将您的查询参数作为关联数组:

There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:

$data = array(
    1,
    4,
    'a' => 'b',
    'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));

会回来

string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"

http_build_query() 为您处理所有必要的转义(%5B => [%5D=> ]),所以这个字符串等于 aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.

http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.

这篇关于将数组作为 url 参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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