【问题标题】:How can I add and manipulate existing GET variables of the current url in php?如何在 php 中添加和操作当前 url 的现有 GET 变量?
【发布时间】:2017-08-25 12:04:14
【问题描述】:

您好,我有这样的网址...

www.example.com/list.php?type=vehicles&stype=Cars
www.example.com/list.php?type=vehicles&stype=Cars&loc=Ludhiana

现在我想根据价格、型号和访问次数对所有结果进行排序。所以我用

$sort="id";
    if(isset($_GET['sort'])){
        if($_GET['sort']=='P-ASC'){ $sort = "price ASC"; }
        elseif($_GET['sort']=='P-DESC'){ $sort = "price DESC"; }
        elseif($_GET['sort']=='R-ASC'){ $sort = "model ASC"; }
        elseif($_GET['sort']=='R-DESC'){ $sort = "model DESC"; }
        elseif($_GET['sort']=='V-ASC'){ $sort = "visits ASC"; }
        elseif($_GET['sort']=='V-DESC'){ $sort = "visits DESC"; }
    }

现在我想在 url 的末尾添加排序变量来对结果进行排序。例如

www.example.com/list.php?type=vehicles&stype=Cars&sort='**ANYVALUE**'
www.example.com/list.php?type=vehicles&stype=Cars&loc=Ludhiana&sort='**ANYVALUE**'

到目前为止,我正在使用的 href 对我来说绝对没问题...

<a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='**Anyvalue**'"

当我尝试操纵排序值时存在问题,例如我有两个href

<a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='P-ASC'"
<a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='P-DESC'"

当我转到第一个 url 时,它工作正常,当我在使用第一个 url 后转到第二个 url 时,URL 在 URL 中添加另一个排序变量导致 URL 中的两个排序变量。我想要的是

  1. 检查这些 GET 变量是否存在?
  2. 如果存在,那么操纵这些变量的值?
  3. 如果不存在,则将新的 get 变量添加到 URL。

【问题讨论】:

    标签: php url get


    【解决方案1】:

    http_build_query($_GET + ['sort' =&gt; 'anyvalue'])

    应该工作

    编辑

    数组的加号这样做

    $a = ['a' => 1, 'b' => 2, 'c' => 3];
    $b = ['a' => 4, 'd' => 5];
    $res = $a + $b;
    

    它从$b 向数组$a 添加键,这些键在$a 中不存在

    这是$res 变量:

    array(4) {
      'a' =>
      int(1)
      'b' =>
      int(2)
      'c' =>
      int(3)
      'd' =>
      int(5)
    }
    

    http_build_query 函数从数组中构建查询字符串。 所以http_build_query($res) 将是:

    a=1&b=2&c=3&d=5
    

    在您的情况下,您可以像这样使用它:

    <a href="?<?php echo http_build_query($_GET + ['sort' => '**AnyValue**']); ?>">link</a>
    

    【讨论】:

    • 嗨 @Petr 我是 PHP 新手,第一次使用这个概念。你能添加更多关于如何使用它的细节吗?谢谢
    • 谢谢@Petr。但它给出了一个PHP错误“解析错误:语法错误,意外'['”
    • 你使用哪个 PHP 版本?
    • 只需将['sort' =&gt; '**AnyValue**'] 替换为array('sort' =&gt; '**AnyValue**')
    • 哦,我的错。对不起。忘记 QUERY_STRING 实际上是字符串:D 试试这个:http_build_query($_GET + array('sort' =&gt; 'abcd'));
    猜你喜欢
    • 2011-03-10
    • 1970-01-01
    • 2021-03-29
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多