Is there a standard way of passing an array through a query string?
To be clear, I have a query string with multiple values, one of which would be an array value.
Check the parse_string
function http://php.net/manual/en/function.parse-str.php
It will return all the variables from a query string, including arrays.
Example from php.net:
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>
You can use http_build_query to generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_query
method, so when it comes to decoding, you can check what separator was used. If it was the unique one you chose, then that would be the array querystring otherwise it would be the normal querystrings.
Although there isn't a standard on the URL part, there is one standard for JavaScript. If you pass objects containing arrays to URLSearchParams
, and call toString()
on it, it will transform it into a comma separated list of items:
let data = {
str: 'abc',
arr: ['abc', 123]
}
new URLSearchParams(data).toString(); // ?str=abc&arr=abc,123
I use React and Rails. I did:
js
let params = {
filter_array: ['A', 'B', 'C']
}
...
//transform params in URI
Object.keys(params).map(key => {
if (Array.isArray(params[key])) {
return params[key].map((value) => `${key}[]=${value}`).join('&')
}
}
//filter_array[]=A&filter_array[]=B&filter_array[]=C