http_build_query with same name parameters

2019-01-06 17:20发布

问题:

Is there a way to build a query automatically with http_build_query using parameters with the same name?

If I do something like

array('foo' => 'x', 'foo' => 'y');

They are obviously overwritten within the array, but even if I do:

array('foo' => array('x', 'y'));

The function creates something like foo[0]=x&foo[1], which isn't what I want, since I need the parameters in this format foo=x&foo=y.

回答1:

This should do what you want, I had an api that required the same thing.

$vars = array('foo' => array('x','y'));
$query = http_build_query($vars, null, '&');
$string = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query); //foo=x&foo=y


回答2:

Here is a function I created to build the query and preserve names. I created this to work with a third-party API that requires multiple query string parameters with the same name.

function create_query_string($query_data) {
    $query = array();
    foreach ($query_data as $name => $value) {
        if (is_array($value)) {
            array_walk_recursive($value, function($value) use (&$query, $name) {
                $query[] = urlencode($name) . '=' . urlencode($value);
            });
        }
        else {
            $query[] = urlencode($name) . '=' . urlencode($value);
        }
    }
    return implode("&", $query);
}

Usage:

echo create_query_string(['a' => 1, 'b' => 2, 'c' => [3, 4]]);

Outputs:

a=1&b=2&c=3&c=4


标签: php http url