0

例如,我有一个这样的 URL:

index.php?country=Canada

如果只是index.php这意味着默认国家是美国。人们可以通过选中或取消选中复选框来切换国家/地区。 但是人们可以通过 GET 变量对结果进行排序:

<a href="<?php $_SERVER["REQUEST_URI"] ?>&sort=state">State</a>
<a href="<?php $_SERVER["REQUEST_URI"] ?>&sort=surname">Surname</a>
<a href="<?php $_SERVER["REQUEST_URI"] ?>&sort=name">Name</a>

但是如果我使用$_SERVER["REQUEST_URI"]它,它总是会不断地向我的 URL 数组(查询字符串)添加新值。如果是这样的话,它就可以工作,index.php我可以这样做:

<a href="<?php $_SERVER["PHP_SELF"] ?>?sort=state">State</a>
<a href="<?php $_SERVER["PHP_SELF"] ?>?sort=surname">Surname</a>
<a href="<?php $_SERVER["PHP_SELF"] ?>?sort=name">Name</a>

我知道,之后index.php它总是首先是一个问号?。但是当访问者想要保留index.php?country=Canada和只是在sort=state, sort=surname and sort=name. 然后我需要知道 URL 中是否已经有问号,何时添加&标记。我不知道如何解决这个问题。

4

4 回答 4

2

更改回显链接的方式:

PHP

<?php
    $link = $_SERVER["PHP_SELF"];
    if(isset($_GET['country']
        $link.="&";
    else
        $link.="?";
?>

和这样的回声链接:

HTML

<a href="<?php $link ?>sort=state">State</a>

注意:我删除了“排序”之前的问号。

于 2013-06-07T15:57:31.997 回答
1

您需要逻辑来动态构建查询字符串,而不是静态添加?and &

就像http_build_query我要走的路线一样,但是与您似乎想要的可能性相比,您提供的信息很小,因此很难提供特定的代码。

http_build_query这是有关PHP中的函数的更多信息。它的目的是构建一个查询字符串,这里是一个你可以做的例子:

// capture the values into variables, however you want ($_GET is example)
$country = $_GET['country'];
$state = $_GET['state'];
$city = $_GET['city'];
$data = array();

// use logic to dynamically build the array, so long as the variables have values
!empty($country) ? array_push($data,'country'=>$country) : '';
!empty($state) ? array_push($data,'state'=>$state) : '';
!empty($city) ? array_push($data,'city'=>$city) : '';

// apply the array dynamically built
$querystring = http_build_query($data);

// concatenate to form the new URL
$url = 'http://www.example.com/?'.$querystring

如果您声明country了 isUSAcityto be Seattle,但没​​有声明state,它将产生:

http://www.example.com/?country=USA&city=Seattle

沿着这些路线的东西应该只使用您正在寻找的值来构建您想要的动态数组。

于 2013-06-07T15:57:19.347 回答
1

查询字符串中的所有变量都存储在$_GETphp 超全局数组中。在您的示例中,您可以使用$_GET['country']. 请默认为美国,您可以使用它isset()来检查变量是否存在。

$country = "USA";
if(isset($_GET['country'])) {
   $country = $_GET['country'];
}
于 2013-06-07T15:58:13.040 回答
1

这里的解决方案是使用$_GET(在另一个答案中已经提到)或http://php.net/manual/en/function.parse-url.php,这使得参数的顺序完全无关紧要。只需将 url 解析为查询参数数组,然后测试您需要的参数。要将其全部转换为 url,您可以使用http://php.net/manual/en/function.http-build-query.php

于 2013-06-07T15:58:25.780 回答