如何在 URL 中传递多个变量,并在未提供的情况下将每个变量替换为默认值

How to pass multiple variables in a URL and have each one replaced by a default value if not supplied

这里需要一点 PHP 帮助。

以下 PHP 代码完美地在给定网站上传递附属 ID,用户将其附属 ID 添加到 URL 的末尾,否则使用默认值(我有一直在成功使用它)。

示例:

www.example.com (uses 'defaultid' from the PHP code)

www.example.com/?id=test1 (uses the affiliate ID 'test1' supplied by the user)

<?php

/* DEFAULT SETTINGS */

$DEFAULT_ID = "defaultid";

/* Function to display ID value */

function displayID($defaultValue) {

global $_GET, $DEFAULT_ID;

if (isset($_GET['id']) and strlen(trim($_GET['id']))) {

 echo $_GET['id'];

} else if (strlen(trim($defaultValue))) {

 echo $defaultValue1;

} else {

 echo $DEFAULT_ID;

}

}

/* End of function to display ID value */

?>

我想知道的是如何修改以上代码以适用于 3 个不同的会员 ID,其中在给定网页上有 3 个超链接用于 3 个不同的会员优惠。

示例:

www.example.com (uses 3 default IDs that I've defined in the code) www.example.com/?id1=test1 (uses default IDs 'defaultid2' and 'defaultid3') www.example.com/?id1=test1&id2=test2 (uses just the default ID 'defaultid3') www.example.com/?id1=test1&id2=test2&id3=test3 (uses the 3 IDs supplied in the URL by the affiliate)

请注意,我不是 PHP 精明的人,因此最好(如果可能)修改以上代码,而不是完全重写,因为我可能无法理解。

好吧,要获得默认值,您可以将此添加到您的代码中:

$id1="test1";
$id2="test2";
$id3="test3";

if (isset($_GET['id1']) && strlen(trim($_GET['id1'])))
   $id1=$_GET['id1'];

if (isset($_GET['id2']) && strlen(trim($_GET['id2'])))
   $id2=$_GET['id2'];

if (isset($_GET['id3']) && strlen(trim($_GET['id3'])))
   $id3=$_GET['id3'];

此代码的工作原理:您有三个变量,每个变量一个 ID

条件语句将验证 $_GET 数组中是否有与此 id 同名的任何内容。如果有则覆盖之前的值,如果没有则保留默认值

另外,如果你是三元的粉丝,这也是一样的,而且看起来更漂亮:

$id1= (isset($_GET['id1']) && strlen(trim($_GET['id1']))) ? $_GET['id1'] : "test1";
$id2= (isset($_GET['id2']) && strlen(trim($_GET['id2']))) ? $_GET['id2'] : "test2";
$id3= (isset($_GET['id3']) && strlen(trim($_GET['id3']))) ? $_GET['id3'] : "test3";