在这种情况下,查询参数“style”是一个数组,必须用方括号标识 - 如果不是,最后一个 key=value 对将覆盖其他对。
?style[]=ranch&style[]=barn&style[]=colonial
$_GET['style']
是一个数组,那么你可以通过使用循环foreach
:
foreach ($_GET['style'] as $value) {
// ...
}
如果 'style' 不是您要添加的唯一参数,您可以在循环中使用is_array()
检查:foreach
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
if(is_array($value)) {
$sec = array();
foreach($value as $second_level) {
$sec[] = $key . " LIKE '%" . $second_level."%'";
}
$sqlStyle .= implode(' AND ', $sec);
}
else {
$sqlStyle .= $key . " LIKE '%" . $value ."%'";
}
$i++;
}
echo $sqlStyle;
没有 foreach 的替代方案:
<?php
$statement = "SELECT DISTINCT COUNT(*) as count FROM `houses_single`";
if(is_array($_GET)) {
$statement .= ' WHERE';
// create copy to keep the $_GET array
$add_where = $_GET;
array_walk(function($elem,$key){
is_array($elem) {
return implode(' AND ', array_map(function($sec) using ($key) {
return "$key LIKE '%$sec%'";
}, $elem);
}
else {
return "$key LIKE '%$elem%'";
}
},$add_where);
$statement .= implode(' AND ', $add_where);
}
(代码未经测试)
Sidenode 关于安全性:我希望您不会在没有任何参数转义的情况下使用您在生产环境中提供的这段代码片段。