0

我有 JSON 响应请求,并希望从它们中创建一个变量 $Where,这是 JSON 模式:

"filter":
{"filters":[
    {"logic":"and","filters":[
        {"field":"NAMA","operator":"eq","value":"Rahmat"},
        {"field":"NAMA","operator":"eq","value":"Rosadi"}
    ]},{"logic":"or","filters":[
        {"field":"NIPK","operator":"eq","value":"1919191919"},
        {"field":"NIPK","operator":"eq","value":"818181818181"}
    ]},{"logic":"and","filters":[
        {"field":"JK","operator":"eq","value":"P"},
        {"field":"JK","operator":"eq","value":"L"}
    ]}
],
"logic":"and"}

谁能告诉我如何使这种模式像这样单行 PHP 变量:

$Where = "(NAMA = 'Rahmat' or NAMA = 'Rosadi') and (NIPK = '1919191919' or NIPK != '818181818181') and (JK='P' AND JK='L')"

对不起,我的英语不好。

4

1 回答 1

1

您可以将列表枚举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);
于 2012-09-17T13:42:26.817 回答