Passing ever-changing PHP query strings

I have a list of articles on my page, and I would like to apply a lot of types and filters to them by adding $ _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 add these values ​​to url ... they should be smart enough to take into account any previous sortings / filters.

Example 1:

if I have ... http://www.example.com/blogs.php?sort=newest

and then I want to add an additional popularity filter = high, I need to have this:

http://www.example.com/blogs.php?sort=newest&popularity=high

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'm trying to change the popularity filter, I don't want:

http://www.example.com/blogs.php?popularity=high&popularity=low

therefore, just binding to the query string will not be performed.

So, what is a scalable way to create filter links so that they “remember” old filters, but overwrite their own filter value if necessary?

+3
source share
4 answers

You can store your filters in an associative array:

$myFilters = array(
                      "popularity" => "low",
                      "sort" => "newest"
);

, , , 1 . http_build_query :

$myURL = 'http://www.example.com/test.php?' . http_build_query($myFilters);

URL-:

http://www.example.com/test.php?popularity=low&sort=newest

: , querystring , URL-:

asort($myFilters);
$myURL = 'http://www.example.com/test.php?' . http_build_query($myFilters);
+9

array_merge GET :

$_GET = array('sort'=>'newest');

$params = array_merge($_GET, array('popularity'=>'high'));
// OR
$params = array('popularity'=>'high') + $_GET;

http_build_query .

+2

- . :

$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.
+1

, , :

writeLink ($ baseURL, $currentFilters, $AdditionalFilters)

This function can determine if additional filters should overlap or remove entries from $ currentFilters, then it can display the entire URL at once using http_build_query

0
source

Source: https://habr.com/ru/post/1718923/


All Articles