用 http_build_query 对 url 进行编码:
http_build_query 可以将一维或多维 数组/对象 进行 url_encode 编码,并返回编码后的字符串。
它的方便之处在于,可以直接将对象或数组编码,省去了许多体力劳动。
by the way,无论传入的数据是数组还是 object,解码后都将转换为数组。
$a = new stdClass(); // 初始化 object a
$b = array(); // 初始化数组 b
$a->val1 = 'a1';
$b = [
'val1' => 'abcd',
'val2' => 'efgh'
];
$a->cc = $b; // 将数组 b 插入 object a
$encode = http_build_query($a); // 编码
$url = 'http://127.0.0.1/req.php?'. $encode; // 生成地址
echo '<a href="'. $url. '">'. $url. '</a>'; // 生成链接

我们在 req.php 中简单的 var_dump $_GET 变量,查看传来的值:

http_build_query 的第二个参数只针对数字索引的数组,当我们的数组中存在数字索引时,可以在第二个参数中指定索引的前缀:
$a = array(); // 初始化数组 b
$a = [
'one', // 数字索引键
'two', // 数字索引键
'aa' => 'bb'
];
$encode = http_build_query($a, 'req_'); // 带有前缀的编码
接受的数据为:

网友评论