好吧,我花了一些时间来解决这个问题。我能想到的最好的如下。基本上,该函数接受一个填充了必要参数的键/值对的数组。它首先遍历参数/s 以找到总计数,然后在前端应用必要的括号。然后它通过一系列循环解析参数并根据需要附加它们。
该解决方案特定于 Mochi Feed API,但如果您稍作调整,它可以以其他方式使用。
// Accepts: $params (array) - An array which contains all of the filter options we are trying to account for.
function process_feed($params=null) {
// Grab our feed's base URL
$url = 'http://the.apiurl.com/f/query/?q=';
// The items stored in this array can be set to a boolean value (true or false)
$bool_queries = array('rev_enabled', 'this_enabled', 'this_also_enabled');
// The items stored in this array can be set to an integer, string, etc...
$return_queries = array('languages', 'omit_tags', 'tags', 'category', 'limit');
// Grab the parameter/filter count
$size = count($params);
// We have enough filters to go custom
if ($size > 1) {
// Loop through and place the appropriate amount of opening parens
for ($x = 0; $x < ($size-1); $x++) { $url .= '('; }
$i = 0;
foreach ($params as $key=>$value) {
if ($i < ($size-1)) {
if (in_array($key, $bool_queries)) {
$url .= $key.')%20and%20';
} else {
// special NOT case
if ($key == 'omit_tags') {
$url .= 'not%20tags%3A'.$value.')%20and%20';
} else {
$url .= $key.'%3A'.$value.')%20and%20';
}
}
} else {
if (in_array($key, $bool_queries)) {
$url .= $key;
} else {
// special NOT case
if ($key == 'omit_tags') {
$url .= 'not%20tags%3A'.$value;
} else {
$url .= $key.'%3A'.$value;
}
}
}
$i++;
}
} else if ($size == 1) {
foreach ($params as $key=>$value) {
if (in_array($key, $bool_queries)) {
$url .= $key;
} else {
// special NOT case
if ($key == 'omit_tags') {
$url .= 'not%20tags%3A'.$value;
} else {
$url .= $key.'%3A'.$value;
}
}
}
}
if (isset($params['limit'])) {
$url .= '&partner_id=' . $our_partner_key . '&limit=' . $limit;
} else {
$url .= '&partner_id=' . $our_partner_key;
}
if(isset($url)) {
return $url;
}
return false;
}