使用数组中的参数生成 URL

2022-08-30 08:37:55

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

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

并生成一个 URL,例如 http://example.com?s1=one&s2=two&s3=three=&s4=four&s5=five&s6=six

并非所有子项都已定义,因此有时可能未定义 s3,因此不应将其追加到 URL。此外,无论第一个子项是什么,它都必须具有 ?在它前面而不是与号 (&)

因此,如果数组只是:

$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提供的任何我都可以使用的话。


答案 1

您所需要的只是http_build_query

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

答案 2

您可以与函数一起使用。php.net 示例:http_build_query()

<?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

玩得愉快。:)