是否可以简化PHP中用于构建URL参数的一系列if
语句?如果?
可能&
,我将如何在第一个参数之前添加$var1
,为其余参数添加0
?
以下是我想要做的一个例子:
<?php
$var1 = 1;
$var2 = 1;
$var3 = 0;
$var4 = 1;
$urlparam = "";
if ($var1 == 1) $urlparam = $urlparam . "?var1=".$var1;
if ($var2 == 1) $urlparam = $urlparam . "&var2=".$var2;
if ($var3 == 1) $urlparam = $urlparam . "&var3=".$var3;
if ($var4 == 1) $urlparam = $urlparam . "&var4=".$var4;
echo "http://example.com/index.php" . $urlparam;
// http://example.com/index.php?var1=1&var2=1&var4=1
?>
答案 0 :(得分:6)
$vars = array(
'var1' => 1,
'var2' => 1,
'var3' => 0,
'var4' => 1
);
$vars = array_filter($vars);
$urlparam = '?' . http_build_query($vars);
$vars
包含我们可能希望在查询字符串中放入的值数组array_filter()
删除任何零(错误)值http_build_query()
使用剩余值