【问题标题】:Passing constantly changing query strings PHP传递不断变化的查询字符串 PHP
【发布时间】:2009-09-30 16:44:12
【问题描述】:

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

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

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

示例 1:

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

然后我想附加一个流行度=高的附加过滤器,我需要这个:

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

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

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

【问题讨论】:

    标签: php url get query-string


    【解决方案1】:

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

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

    将过滤器存储在关联数组中可确保每个过滤器只有 1 个值。然后你可以使用http_build_query 来构建你的查询字符串:

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

    这将产生以下网址:

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

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

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

    【讨论】:

    • 如何处理旨在更改这些过滤器之一的链接?链接本身不能更改数组值,然后重新加载页面...对吗?
    • 只需使用您想要放入链接的过滤器构建一个特定数组。
    【解决方案2】:

    使用 array_mergeunion operation 将当前 GET 变量与新变量联合起来:

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

    之后,您可以使用http_build_query 或您自己的查询构建算法。

    【讨论】:

      【解决方案3】:

      最好的方法是手动编译查询字符串。例如:

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

      【讨论】:

        【解决方案4】:

        您似乎应该使用如下所示的签名编写自己的函数:

        函数 writeLink($baseURL, $currentFilters, $additionalFilters)

        这个函数可以确定额外的过滤器是否应该覆盖或删除 $currentFilters 中的条目,然后它可以使用 http_build_query 一次输出整个 URL

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-25
          • 2017-11-15
          • 2012-06-25
          相关资源
          最近更新 更多