如何为我的网页添加以下http_build_query
脚本?
$params = array(
'p' => 'foo',
'lang' => 'bar'
);
echo http_build_query($params); // p=foo&lang=bar
echo '?' . http_build_query($params); // ?p=foo&lang=bar
与PHP url strings conflict "?" and "&"
相关以下是我的网页的工作原理:
<a href="?lang=es">Español</a>
<a href="?lang=en">English</a>
<?php
$p = $_GET['p'];
$pages = array('g1', 'g2', 'g3');
if (!empty($p)) {
if(in_array($p,$pages)) {
$p .= '.php';
include($p);
}
}
else {
echo '<a href="?p=g1">Page 1</a> <a href="?p=g2">Page 2</a></li> <a href="?p=g3">Page 3</a>';
}
?>
答案 0 :(得分:2)
您可以编写一个函数来将查询参数与当前$_GET
数组合并。
<?php
function merge_queries(array $original, array $updates) {
$params = array_merge($original, $updates);
return '?'.http_build_query($params);
}
?>
<a href="<?php echo merge_queries($_GET, array('lang'=>'es')); ?>">Español</a>
<a href="<?php echo merge_queries($_GET, array('lang'=>'en')); ?>">English</a>
<?php
// code abbreviated for clarity
echo '<a href="'.merge_queries($_GET, array('p'=>'g1')).'">Page 1</a>
<a href="'.merge_queries($_GET, array('p'=>'g2')).'">Page 2</a>
<a href="'.merge_queries($_GET, array('p'=>'g3')).'">Page 3</a>';
?>
答案 1 :(得分:0)
你可以很容易地做到这一点:
$urlpath = implode('&', $params);
$url = $yourhost . '?' . $urlpart;