Parse Query String into an Array

Parse query string into an array

You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.

$get_string = "pg_id=2&parent_id=2&document&video";

parse_str($get_string, $get_array);

print_r($get_array);

PHP parse query string to associative array

Thanks to Dharman

parse_str() worked as I wanted. However parse_str() does not return the parsed variables. It just creates the variable in current scope.

parse QueryString in javascript

A few suggestions - consider using window.location.search to access the query string directly.

Also, you might want to factor in scenarios where "arrays" exist in your query string (ie multiple values sharing the same key). One way to handle that might be to return an array of values found for a key, in the data object that you return.

For more detail, see the comments in this updated version of the function:

function parseQueryString() {

// Use location.search to access query string instead
const qs = window.location.search.replace('?', '');

const items = qs.split('&');

// Consider using reduce to create the data mapping
return items.reduce((data, item) => {

const [rawKey, rawValue] = item.split('=');
const key = decodeURIComponent(rawKey);
const value = decodeURIComponent(rawValue);

// Sometimes a query string can have multiple values
// for the same key, so to factor that case in, you
// could collect an array of values for the same key
if(data[key] !== undefined) {

// If the value for this key was not previously an
// array, update it
if(!Array.isArray(data[key])) {
data[key] = [ data[key] ]
}

data[key].push(value)
}
else {

data[key] = value
}

return data

}, {})
}

Parse just one query string parameter into Javascript array

Assuming that the order of your query strings aren't always going to be known and that you have to support finding 'q' anywhere;

// substring(1) to skip the '?' character
var queryStrings = window.location.search.substring(1).split('&');
var qArray;
for (var i = 0; i < queryStrings.length; i++) {
if (queryStrings[i].substring(0, 2) === 'q=') {
qArray = queryStrings[i].substring(2).split('+');
break;
}
}


Related Topics



Leave a reply



Submit