使用数组中的参数生成 URL [英] Generate URL with parameters from an array

查看:19
本文介绍了使用数组中的参数生成 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要像下面这样的数组:

I need to take an array like I have below:

$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

and generate a URL such as http://example.com?s1=one&s2=two&s3=three=&s4=four&s5=five&s6=six

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

All of the subids are not always defined, so sometimes s3 may not be defined, so it shouldn't be appended to the URL. Additionally, whatever the first subid is, it has to have the ? preceding it instead of the ampersand (&)

所以如果数组只是:

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

那么 URL 需要是 http://example.com?s2=two&s6=六个

then the URL needs to be http://example.com?s2=two&s6=six

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

I have the following so far:

$url = 'http://example.com'

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

但是,我不确定附加 ?在第一个键/值对的开头.

However, I'm not sure what the best way would be to append the ? at the beginning of the first key/value pair.

我觉得有一个 PHP 函数可以帮助解决这个问题,但我没有找到太多.如果我可以使用 CI 提供的任何东西,我将使用 Codeigniter.

I feel like there's a PHP function to help with this but I'm not finding much. I'm using Codeigniter if there's anything I can use that is provided by CI.

推荐答案

您只需要 http_build_query:

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

这篇关于使用数组中的参数生成 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆