Apache重写查询字符串(复选框数组)

jan*_*jan 4 php wordpress mod-rewrite url-rewriting

如何重写查询字符串如:

test.php?cat1[]=18&cat1[]=687&xxx[]=5&xxx[]=3&xxx[]=1&yyy[]=6
Run Code Online (Sandbox Code Playgroud)

test.php?cat1=18,687,5&xxx=3,1&yyy=6
Run Code Online (Sandbox Code Playgroud)

请注意,参数(名称和值对)是动态生成的.

Jon*_*Lin 8

这是一个简短的PHP脚本,可以创建您想要的查询字符串.最好不要使用mod_rewrite来执行此部分,因为它只是在该范围之外:

<?php

$ret = "";
foreach($_GET as $key=>$val) {
  if(is_array($val)) {
    // Create the comma separated string
    $value = $val[0];
    $length = count($val);
    for($i=1; $i < $length; $i++) {
      $value .= ',' . $val[$i];
    }
    $ret .= "$key=$value&";
  } else {
    $ret .= "$key=$val&";
  }
}

// Remove last '&'
$ret = substr($ret , 0, strlen($ret)-1);

// Redirect the browser
header('HTTP/1.1 302 Moved');
header("Location: /test.php?" . $ret);

?>
Run Code Online (Sandbox Code Playgroud)

/rewrite.php例如,如果将该脚本保存为,则可以在.htaccess文件中包含这些规则,以使用包含数组的查询字符串重新路由请求/rewrite.php:

RewriteCond %{QUERY_STRING} \[\]
RewriteRule ^test.php /rewrite.php [L,QSA]
Run Code Online (Sandbox Code Playgroud)

然后,rewrite.php脚本将重写查询字符串并使用连接的查询字符串重定向浏览器.