php http_build_query() 将数组生成URL查询字符串

时间:2016-06-30
php http_build_query()函数的作用是将一个数组转换成url 问号?后面的参数字符串,并且会自动进行urlencode处理。本文章向大家讲解php http_build_query()函数的使用技巧,需要的朋友可以参考一下。

使用一维数组

$data = array(
	'foo'=>'bar', 
	'baz'=>'boom', 
	'site'=>'www.nowamagic.net', 
	'name'=>'nowa magic'); 
	
echo http_build_query($data); 

/* output 
	foo=bar&baz=boom&cow=milk&php=hypertext+processor 
*/ 

如果是索引数组与关联数组混合而成的数组又如何呢?

$data = array(
	'foo',
	'bar', 
	'site'=>'www.xxxx.com', 
	'name'=>'manongjc'); 
	
echo http_build_query($data); 

/* output 
	0=foo&1=bar&site=www.xxx.com&name=manongjc
*/ 

它会自动添加数字索引。

http_build_query 还有一个参数,可以给数字索引加前缀,我们再试试:

$data = array(
	'foo',
	'bar', 
	'site'=>'www.xxx.com', 
	'name'=>'manongjc'); 
	
echo http_build_query($data, "nm_"); 

/* output 
	nm_0=foo&nm_1=bar&site=www.xxx.com&name=manongjc
*/ 

再复杂一些的数组又如何呢?比如二维数组什么的。

$data = array(
	'user'=>array(	'name'=>'Bob Smith', 
					'age'=>47, 
					'sex'=>'M', 
					'dob'=>'5/12/1956'), 
	  'pastimes'=>array('golf', 'opera', 'poker', 'rap'), 
	  'children'=>array('bobby'=>array('age'=>12, 
									   'sex'=>'M'), 
						'sally'=>array('age'=>8, 
									   'sex'=>'F')), 
	  'CEO'); 

结果:

user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&user%5Bdob%5D=5%2F12%2F1956
&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&pastimes%5B2%5D=poker
&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&children%5Bbobby%5D%5Bsex%5D=M
&children%5Bsally%5D%5Bage%5D=8&children%5Bsally%5D%5Bsex%5D=F&0=CEO