Alex Rivera | Logout

php url query nested array with no index

Asked 2012-08-16T22:53:50.517
17

I'm working with a third party API that receives several parameters which must be encoded like this:

text[]=Hello%20World&text[]=How%20are%20you?&html[]=<p>Just%20fine,%20thank%20you</p>

As you can see this API can accept multiple parameters for text, and also for HTML (not in the sample call).

I have used http_build_query to correctly build a query string for other APIs

$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';

$http_query = http_build_query($params);

The problem with this approach is that it will build a query string with the numeric index:

text[0]=Hello%20World&text[1]=How%20are%20you?&html[0]=<p>Just%20fine,%20thank%20you</p>

unfortunately the API I'm working with doesn't like the numeric index and fails.

Is there any php function/class-method that can help me build a query like this quickly?

Thank you

Edit
Report

1 Answer

1

Try this:

$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';
foreach ($params as $key => $value) {
    foreach ($value as $key2 => $value2) {        
        $http_query.= $key . "[]=" . $value2 . "&";
    }
}
$http_query = substr($http_query, 0, strlen($http_query)-1); // remove the last '&'
$http_query = str_replace(" ", "%20", $http_query); // manually encode spaces
echo $http_query;
answered 2012-08-16T23:11:15.013

Your Answer