sending array via query string in guzzle

Peter Krejci picture Peter Krejci · Dec 18, 2012 · Viewed 8.6k times · Source

Guzzle client creates by default from this code

$client->get('https://example.com/{?a}', array('a' => array('c','d')));

this url

https://example.com/?a=c,d

What is the best practice to send array in query string in RESTful application? The question is, how can I determine on the server side whether c,d is a string or an array? Isn't it better to send arrays using square brackets, e.g. a[]=c&a[]=d? How can I set Guzzle to use square brackets? Or it is better to use JSON encoded variables? On the server side I'm using Tonic.

Answer

Dung picture Dung · Feb 19, 2016

Working Solution:

$vars = array('state[]' => array('Assigned','New'), 'per_page' => $perPage, 'page' => $pageNumber);
$query = http_build_query($vars, null, '&');
$string = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $query); // state[]=Assigned&state[]=New
$client = new Client([follow instruction to initialize your client ....]);
$response = $client->request('GET', $uri, ['query' => $string]);

Now you have same name parameters in your request.

Dung.

Source: http_build_query with same name parameters