我必须构建一个高级搜索功能,其中一些选项很复杂。例如:
- 在线
- 有评论
- ETC
要获取此信息,我无法进行直接数据库查询。所以,我需要构建函数来做到这一点。
假设...用户选择 4 或 5 个选项 - 如何组合多个功能结果?
这样做是没有意义的:
if(is_Online() && have_Comments()...)
因为我不知道选择了哪些或多少个选项......所以我认为应该有一些动态的选择?
谢谢你。
我必须构建一个高级搜索功能,其中一些选项很复杂。例如:
要获取此信息,我无法进行直接数据库查询。所以,我需要构建函数来做到这一点。
假设...用户选择 4 或 5 个选项 - 如何组合多个功能结果?
这样做是没有意义的:
if(is_Online() && have_Comments()...)
因为我不知道选择了哪些或多少个选项......所以我认为应该有一些动态的选择?
谢谢你。
Difficult to provide a better answer without more detail, but this might help you. The following assumes that your if statement will proceed when each checkbox is either left unchecked or when the logic associated with that checkbox returns true.
I would be inclined to store each function in an array and call them dynamically based on the name of the field you're looking at.
<?php
$resultCheckers = array(
'is_Online' => function() { /* Is Online logic here */},
'have_Comments' => function() { /* Have Comments logic here */}
);
function IsUncheckedOrHasValue($parameter)
{
$result = true;
//Check if user has checked the box for this parameter
if(array_key_exists($parameter, $_POST))
{
//Check if this is a valid key in your $resultCheckers
if(array_key_exists($parameter, $resultCheckers))
{
//Run the result Checker
$result = $resultCheckers[$parameter]();
} else {
$result = false;
}
}
return $result;
}
?>
Your if statement would look something like this:
if(IsUncheckedOrHasValue('is_Online') && IsUncheckedOrHasValue('have_Comments'))
{
...
}
Which is a bit laborious to read, so if you wanted you could abstract it further into it's own function like this:
function IsMatch()
{
$isMatch = IsUncheckedOrHasValue('is_Online') &&
IsUncheckedOrHasValue('have_Comments') &&
IsUncheckedOrHasValue(...) &&
IsUncheckedOrHasValue(...);
return $isMatch;
}
So then your if statement would end up being
if(IsMatch())
{
...
}
NOTE: I'm a little confused that you're not passing any information about the result to your checking functions. Are you writing it Object Oriented and that information is available in the current object? Or perhaps you just omitted those extra parameters for brevity. In any event, I hope this helps you and it was fun to dip back into PHP after some time away from it :)