您可以将列表枚举filters
到 PHP 数组中,将它们中的每一个构建为 SQL OR 值的列表,然后使用 ; 将它们连接起来implode(' OR ', ...)
。并进一步将数组内爆到“ AND ”子句列表中。
但是,这种方法失去了 JSON 设置所允许的大部分灵活性;它可以扩展到AND
- 子句OR
或单个子句的列表,并且可能OR
使用语法合并同一字段的子句IN
,但仅此而已。
您可以查看从 RPN 表示法转换为代数的算法,以寻找更强大(尽管更复杂)的方法。
简单的版本是
$ops = array(
'eq' => '=',
'ne' => '!=',
'gt' => '>',
'lt' => '<',
'ge' => '>=',
'le' => '<=',
// CHECK THIS OUT, FIX & COMPLETE
);
$arr_Filters = array();
foreach($filters as $filter)
{
/* $filter is a set of subfilters:
{"logic":"and","filters":[
{"field":"NAMA","operator":"eq","value":"Rahmat"},
{"field":"NAMA","operator":"eq","value":"Rosadi"}
]},
which we see as:
*/
$logic = $filter['logic'];
$arr_Filter = array();
foreach($filter['filters'] as $fov)
{
$op_f = $fov['operator'];
$op = $ops[$op_f];
$value = /* FUNCTION TO SQL ESCAPE A VALUE */ $fov['value'];
$value = is_numeric($value) ? $value : "'".$value."'";
$arr_Filter[] = "$fov[field] $op $value";
}
$arr_Filters[] = '('.implode(' ' . $filter['logic'] . ' ', $arr_Filter).')';
}
$sql_filter = 'WHERE ' . implode(' AND ', $arr_Filters);
可以检索使用json_decode()
可以这样操作的对象:
// ($ops omitted, same as above)
$arr_Filters = array();
foreach($filters->filter->filters as $filter)
{
/* $filter is a set of subfilters:
{"logic":"and","filters":[
{"field":"NAMA","operator":"eq","value":"Rahmat"},
{"field":"NAMA","operator":"eq","value":"Rosadi"}
]},
which we see as:
*/
$logic = $filter->logic;
$arr_Filter = array();
foreach($filter->filters as $fov)
{
$op_f = $fov->operator;
$op = $ops[$op_f];
$value = /* FUNCTION TO SQL ESCAPE A VALUE */ $fov->value;
$value = is_numeric($value) ? $value : "'".$value."'";
$arr_Filter[] = "{$fov->field} $op $value";
}
$arr_Filters[] = '('.implode(' ' . $filter->logic . ' ', $arr_Filter).')';
}
$sql_filter = 'WHERE ' . implode(' ' . $filters->filter->logic . ' ', $arr_Filters);