Reputation: 13330
I have a list of articles on my page, and I would like to be able to apply a myriad of sorts and filters to it by appending $_GET values to the URL:
http://www.example.com/blogs.php?sort=newest&popularity=high&length=200
If I have links on my page to append these values to the url...they need to be smart enough to account for any previous sorts/filters applied.
EXAMPLE 1:
if i currently have... http://www.example.com/blogs.php?sort=newest
and then i want to attach an additional filter of popularity=high, i need to have this:
http://www.example.com/blogs.php?sort=newest&popularity=high
and not this:
http://www.example.com/blogs.php?popularity=high
EXAMPLE 2:
if i have... http://www.example.com/blogs.php?popularity=high
and i try to alter my popularity filter, i do not want:
http://www.example.com/blogs.php?popularity=high&popularity=low
so simply tacking on to the query string won't fly.
Therefore, what is a scalable way to build my filter links so that they "remember" old filters, but will still overwrite their own filter value when needed?
Upvotes: 3
Views: 860
Reputation: 655239
Use array_merge
or the union operation to unite the current GET variables with new ones:
$_GET = array('sort'=>'newest');
$params = array_merge($_GET, array('popularity'=>'high'));
// OR
$params = array('popularity'=>'high') + $_GET;
After that you can use http_build_query
or your own query building algorithm.
Upvotes: 2
Reputation: 25205
it seems like you should wirte your own function with a signature that looks something like this:
function writeLink($baseURL, $currentFilters, $additionalFilters)
This function can determine if additional filters should override or remove entries from $currentFilters, then it can output the entire URL at once using http_build_query
Upvotes: 0
Reputation: 2186
You can store your filters in an associative array :
$myFilters = array(
"popularity" => "low",
"sort" => "newest"
);
Having your filters stored in an associative array ensures you only have 1 value for each of them. Then you can use http_build_query to build your querystring :
$myURL = 'http://www.example.com/test.php?' . http_build_query($myFilters);
This will result in the following URL :
http://www.example.com/test.php?popularity=low&sort=newest
Edit : Oh, and if the filters order in the querystring matters, you can sort the associative array before building your URLs :
asort($myFilters);
$myURL = 'http://www.example.com/test.php?' . http_build_query($myFilters);
Upvotes: 9
Reputation: 50298
The best way to do this is to compile the query string manually. For instance:
$str = '?';
$str .= (array_key_exists('popularity', $_GET)) ? 'popularity='.$_GET['popularity'].'&' : '';
$str .= (array_key_exists('sort', $_GET)) ? 'sort='.$_GET['sort'].'&' : '';
// Your query string that you can tack on is now in the "str" variable.
Upvotes: 1