Reputation: 164
I have an ajax system in place that filters results for a clients website.
We're implementing a filter for "venue type". Each checkbox will be named as: venuetype[typeHere].
Now obviously this will be passed to PHP like that, but all I am interested in is the typeHere part.
I need to check that venuetype is in the array, if it is then remove the venuetype[] and be left with just typeHere.
My PHP script is as follows:
$select = 'SELECT *';
$from = ' FROM venues';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("nocorkage", $opts)){
$where .= " AND nocorkage = 1";
}
if (in_array("hotel", $opts)){
$where .= " AND hotel = 1";
}
if (in_array("selfcatering", $opts)){
$where .= " AND selfcatering = 1";
}
if (in_array("marquees", $opts)){
$where .= " AND marquees = 1";
}
if (in_array("inhousecatering", $opts)){
$where .= " AND inhousecatering = 1";
}
if (in_array("outsidecatering", $opts)){
$where .= " AND outsidecatering = 1";
}
if (in_array("licensed", $opts)){
$where .= " AND licensed = 1";
}
if (in_array("venuetype", $opts)){
// Function to go here
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
while($output = $statement->fetch(PDO::FETCH_ASSOC))
{
$return[]=array('id'=>$output['id'],
'title'=>$output['title'],
'main_image'=>$output['main_image']);
}
$json = json_encode($return);
echo($json);
?>
Could someone give me an idea of what I need to do, I was thinking PHP regex... Would this suffice?
Upvotes: 0
Views: 73
Reputation: 6565
lil bit off-topic
i would create my code like
function setWhere($array,$opts,&$where){
foreach($array as $arr){
if(in_array($arr,$opts))
$where .= " AND {$arr} = 1";
}
}
$wAarray = array("nocorkage",
"hotel",
"selfcatering",
"marquees",
"inhousecatering",
"outsidecatering",
"licensed");
setWhere($wArray, $opts, $where);
//... more if your code
instead of X if statements
Explanation: Question was: Why does $where has an ampersand befor?
It's a reference to the variable
Example:
$foo = "hello";
$bar = "world";
function doSomething($str){
return $str;
}
echo $bar; //outputs: world
$bar = doSomething($foo);
echo $bar; //outputs: hello
same with reference
$foo = "hello";
$bar = "world";
function doSomething(&$str){
$str = $foo;
}
echo $bar; //outputs: world
doSomething($bar);
echo $bar; //outputs: hello
Upvotes: 1
Reputation: 2250
Not completely sure this is what you need, but if you use:
foreach($opts["venuetype"] as $typeHere => $venuetype){
// $typeHere will iterate all the key names in the venuetype array
}
Upvotes: 0