php将字符串转换为条件语句

时间:2015-10-29 17:09:13

标签: php arrays 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
);

我需要找到一种方法来编写一个函数来过滤传递" text"过滤为输入:

//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条件语句?

1 个答案:

答案 0 :(得分:0)

我认为这是最简单的方法:

$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代码作为提取值的条件。