说说http_build_query这个函数,在用的时候还是有一些要注意的地方的。

常用的方法是这样的:

	$query = [
		'key1' => 1,
		'key2' => 'v2',
		'key3' => 10.9,
	];

	echo http_build_query($query);

结果是

key1=1&key2=v2&key3=10.9

它会自动urlencode

	$query = [
		'key1' => 1,
		'key2' => 'v2,%4',
		'key3' => 10.9,
	];

	echo http_build_query($query);

结果是把逗号,百分号都转码了

key1=1&key2=v2%2C%254&key3=10.9

但是在不希望urlencode的地方就很难过了,不能用这个方法,而要手动拼凑url。

数组不会自动转变成数组形式

	$query = [
		'key1' => 1,
		'key2' => ['v2', 'v3', 'v4'],
	];

	echo http_build_query($query);

结果是:

key1=1&key2%5B0%5D=v2&key2%5B1%5D=v3&key2%5B2%5D=v4

urldecode一下,是这样的key1=1&key2[0]=v2&key2[1]=v3&key2[2]=v4

可是我不想这样啊!!!我想要的是key1=1&key2=[v2,v3,v4]╮( ̄▽ ̄)╭

要想实现目标,有两种办法:

办法一、使用json_encode

办法二、使用implode

先看办法一:

$query = [
		'key1' => 1,
		'key2' => json_encode(['v2', 'v3', 'v4']),
	];

	echo http_build_query($query);

结果是

key1=1&key2=%5B%22v2%22%2C%22v3%22%2C%22v4%22%5D 

urldecode一下,是这样的key1=1&key2=["v2","v3","v4"]

再看办法二:

$query = [
		'key1' => 1,
		'key2' => ['v2', 'v3', 'v4'],
	];

$query['key2'] = '[' . implode(',' $query['key2']) . ']';
echo http_build_query($query);

结果是

key1=1&key2=%5Bv2%2Cv3%2Cv4%5D

urldecode一下,是这样的key1=1&key2=[v2,v3,v4]