PHP中WHERE的动态参数JSON

时间:2012-09-17 13:18:43

标签: php sql arrays json object

我有JSON响应请求并希望创建一个变量$从哪里来,这是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')"

抱歉我的英语不好。

1 个答案:

答案 0 :(得分: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);