[英]php convert string into conditional statements
我有一个具有齐次值的二维数组。
$input = array(
'x' => 100, 'y' => 101, 'type' => 'yes', value => 10
), array(
'x' => 110, 'y' => 101, 'type' => 'no', value => 10
), array(
'x' => 120, 'y' => 102, 'type' => 'yes', value => 99
);
我需要找出一种方法来编写函数以通过“文本”过滤器作为输入来过滤值:
//extract all values when $tye = yes and $value is greater than 10
custom_filter($input, "type = yes and value > 10");
//extract all values when $x is equal to $y
custom_filter($input, "x = y");
//filter all values for x is pair and y is odd
custom_filter($input, "x % 2 = 0 and y % 2 > 0");
function custom_filter($input_array, $condition) {
(...)
}
有没有一种方法可以将$ condition参数从人类可读的语句转换为php条件语句?
我认为这是最简单的方法:
$input = [
['x' => 100, 'y' => 101, 'type' => 'yes', 'value' => 10],
['x' => 110, 'y' => 101, 'type' => 'no', 'value' => 10],
['x' => 120, 'y' => 102, 'type' => 'yes', 'value' => 99]
];
function custom_filter($array, $eval) {
$validate = function ($item) use($eval) {
extract($item);
eval('$valid = ' . $eval . ';');
return $valid;
};
return array_filter($array, $validate);
}
//extract all values when $tye = yes and $value is greater than 10
var_dump(custom_filter($input, '$type == "yes" && $value > 10'));
//extract all values when $x is equal to $y
var_dump(custom_filter($input, '$x == $y'));
//filter all values for x is pair and y is odd
var_dump(custom_filter($input, '$x % 2 == 0 && $y % 2 > 0'));
好吧,您必须编写一个php代码作为提取值的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.