我使用以下代码回显网址:
echo '<a class="list-group-item" href="'._siteurl.'/search.php?Location='.$Location.'&Select='.$Select.'&countrySelect='.$countrySelect.'&type='.$type.'" title="'.$type.' '.$Select.' | '.$Location.' '.$countrySelect.'">'.$type.'</a>';
有时参数/参数有空值,我想删除这些参数。
我试过if else函数,但它需要包含所有可能性,是否有更好的方法来删除空参数?
答案 0 :(得分:2)
在开始任何输出之前,您应该组装一个参数数组,这样就可以过滤掉空值等:
$Location = 'Somewhere';
//$Select = 'John';
$countrySelect = 'USA';
$params = array(
'Location' => $Location,
'Select' => $Select,
'countrySelect' => $countrySelect,
'type' => $type
);
echo '<a class="list-group-item" href="/search.php?' . http_build_query($params) . '" title="'.$type.' '.$Select.' | '.$Location.' '.$countrySelect.'">'.$type.'</a>';
http_build_query()
will not use any array entries that don't have values(为您过滤!)。
请记住,如果以这种方式编写代码,您将收到未定义的变量警告。最好在向数组中添加值之前有条件地检查,而不是添加所有内容,无论它是否存在,然后过滤掉那些不存在的内容。
修改:如果http_build_query()
由于某种原因没有为您删除空值,请同时使用array_filter()
:
$params = array(
// ...
);
$params = array_filter($params);