使用数组中的参数生成 URL

我需要像下面这样获取一个数组:

$subids = Array
(
[s1] => one
[s2] => two
[s3] => three
[s4] => four
[s5] => five
[s6] => six
)

并生成诸如 http://example.com?s1=one&s2=two&s3=three=&s4=four&s5=five&s6=six之类的 URL

并不总是定义所有的 subid,因此有时可能没有定义 s3,所以不应该将它附加到 URL。此外,无论第一个 subid 是什么,它都必须具有?在它之前而不是与号(&)

所以如果数组只是:

$subids = Array
(
[s2] => two
[s6] => six
)

那么 URL 必须是 http://example.com?s2=two&s6=six

到目前为止,我有以下几点:

$url = ‘ http://example.com

    foreach ($subids AS $key => $value) {
$result[$id]['url'] .= '&' . $key . '=' . $value;
}

然而,我不知道什么是最好的方法将附加的?在第一个键/值对的开头。

我觉得有一个 PHP 函数来帮助这一点,但我没有找到太多。我正在使用 Codeigniter,如果有什么我可以使用,是由 CI 提供的。

94855 次浏览

你所需要的就是 http_build_query:

$final = $url . "?" . http_build_query($subids);

可以与 http_build_query()函数一起使用。 来自 php.net 的例子:

<?php
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'php' => 'hypertext processor',
);


echo http_build_query( $data ) . "\n";
echo http_build_query( $data, '', '&amp;' );
?>

然后输出这一行:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

您可以从源代码中读取: http://www.php.net/manual/en/function.http-build-query.php

顺便说一下,如果你使用 WordPress,你可以这个函数: http://codex.wordpress.org/Function_Reference/add_query_arg

玩得开心

您可以使用 http_build_query()函数,但是一定要做一些验证,如果 URL 来自外部函数,例如。

$url = getUrlSomewhere();
$params = ['param' => 'value', 'param2' => 'value2'];
$queryParams = http_build_query($params);
if (strpos($url, '?') !== FALSE) {
$url .= '&'. $queryParams;
} else {
$url .= '?'. $queryParams;
}

如果您有 PECL 扩展,您可以使用 http_build_url(),它已经考虑到如果您添加更多的参数到一个预先存在的 URL,或没有其他验证。