很多时候,程序都是直接写好逻辑运算,提供给用户的是一个值,然后后台去比较;但是有时会提供一种类似计算器一样的交互方式的时候,PHP只能读懂用户的输入来进行比较了~
最近的一个项目涉及到一个由用户自定义输入比较方法,后台取相应数据,自动比较,输出结果。比如:
用户输入: time>9&&time<15
后台执行: 读懂输入,获取数据,进行比较,输出比较的结果
看了需求,完全就是模拟PHP比较运算与数据库操作啊,干吧~~
<?php $datas = json_decode(file_get_contents(INDEXJSON),true);// Global Var // print_r($da); $condition = 'size>102400&&dir%/var/www/html/wordpress/wp-admin'; print_r(compare($condition)); // getdata for compare function compare($condition){ global $datas; $result = array(); $keys = explode(',', INDEXFORMAT); if (!strpos($condition, '&&')) { $conditions = $condition; }else{ $conditions = explode('&&', $condition); } for($k = 0 ; $k < count($datas['name']) ; $k++) { $flag = true; foreach ($conditions as $subCondition) { if (!getCompare($k, $subCondition)) { $flag = false; break; } } if ($flag) { $result[] = $k; } } return $result;// return keys array in datas } function getCompare($key, $condition){ global $datas; if(!preg_match('/[<>=!%]+/', $condition, $operator)){ //$operator[0] return false; } $value = explode($operator[0], $condition);//x>12 => 12($value) switch ($operator[0]) { case '>': return ($datas[$value[0]][$key] > $value[1]); break; case '>=': return ($datas[$value[0]][$key] >= $value[1]); break; case '<': return ($datas[$value[0]][$key] < $value[1]); break; case '<=': return ($datas[$value[0]][$key] <= $value[1]); break; case '==': return ($datas[$value[0]][$key] == $value[1]); break; case '<>': return ($datas[$value[0]][$key] <> $value[1]); break; case '!=': return ($datas[$value[0]][$key] != $value[1]); break; case '%': if(strpos($datas[$value[0]][$key], $value[1]) === false){ return false; }else{ return true; } break; default: return false; break; } }
注:$data数组格式为
---------- PHP Debugger ----------
Array
(
[name] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
[dir] => Array
(
[0] => F
[1] => E
[2] => D
[3] => C
[4] => B
[5] => A
)
[time] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
)