Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

php - Generate URL with parameters from an array

I need to take an array like I have below:

$subids = Array
    (
        [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

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 (&)

So if the array is just:

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All you need is http_build_query:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...