この場合、クエリパラメータ「style」は配列であり、角かっこで識別する必要があります。そうでない場合、最後のキーと値のペアが他のペアを上書きします。
?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 about safety: I hope you won't use this code snippet you provided in productive environment without any escaping of the parameters.