gpt4 book ai didi

php - 传递不断变化的查询字符串 PHP

转载 作者:可可西里 更新时间:2023-11-01 00:01:42 25 4
gpt4 key购买 nike

我的页面上有一个文章列表,我希望能够通过将 $_GET 值附加到 URL 来对其应用无数种类和过滤器:

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

如果我的页面上有将这些值附加到 url 的链接...它们需要足够智能以说明之前应用的任何排序/过滤器。

示例 1:

如果我现在有... http://www.example.com/blogs.php?sort=newest

然后我想附加一个额外的 popularity=high 过滤器,我需要这个:

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

不是这个:

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

示例 2:

如果我有... http://www.example.com/blogs.php?popularity=high

我试图改变我的人气过滤器,我不想:

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

所以简单地附加到查询字符串上是行不通的。

因此,构建过滤器链接的可扩展方式是什么,以便它们“记住”旧过滤器,但仍会在需要时覆盖它们自己的过滤器值?

最佳答案

您可以将过滤器存储在关联数组中:

$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

编辑:哦,如果查询字符串中的过滤器顺序很重要,您可以在构建 URL 之前对关联数组进行排序:

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

关于php - 传递不断变化的查询字符串 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1499328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com