For an extern (Django) API we need to pass our GET query data to them as follow:
?products=Product1&products=Product2
So as you can see they use different encoding for arrays than the PHP inbuilt
http_build_query(['Product1', 'Product2'])
=> ?products[]=Product1&products[]=Product2
Is there a built in PHP way to build query to get the result the Django API expects? Or do I have to write something my self?
Thanks in advance!
2
Answers
You can use code below
This will get query string like "products=Product1&products=Product2"
That format is not supported natively.
I think the main reason is that URL parameters are a flat key/value structure, while
http_build_query()
can serialise arbitrarily nested arrays and objects. To support that, you need some convention to handle data trees in a flat list. URL specs don’t provide any. PHP uses the[]
notation to mimic arrays elsewhere (e.g.$_GET
), so it makes sense to have such convention in the builtin query creation function.If you are not going to need nested data, you can easily write your own function:
If you’ll need nested data after all, you first have to decide what your naming convention would be.