6

客观的

我正在尝试将复杂的比较存储为 PHP 数组。然后我想读取数组来评估一组变量并返回语句是真还是假。

问题

如何存储复杂的比较,以便以后可以读取并评估当时存在的变量?这是实现这一目标的最佳方法吗?非常感谢您的帮助。

例如,英语

If($source = 200 OR $source = 300) AND ($age < 10 OR $age > 60) THAN 返回 true 否则返回 false

注意: 变量可以是代码中的任意变量,这里我以source和age为例。嵌套数组可以比示例更深或更平坦。

示例,代码

$conditions = Array
(
[relation] => AND
[0] => Array
    (
        [relation] => OR
        [0] => Array
            (
                [var] => source
                [compare] => =
                [value] => 300
            )

        [1] => Array
            (
                [var] => source
                [compare] => =
                [value] => 300
            )

    )

[1] => Array
    (
        [relation] => OR
        [0] => Array
            (
                [var] => age
                [compare] => <
                [value] => 10
            )

        [1] => Array
            (
                [var] => age
                [compare] => >
                [value] => 60
            )

    )

)

解决方案

根据@sam-grondahl 的回答,函数可以处理您可以扔给它的任何嵌套逻辑。接受正则表达式和数字比较

$source = '300';
$age = '60';

$input_variables = array('source' => $source, 'age' => $age);

$conditions = array(
                'relation' => 'and',
                array(
                        'relation' => 'and',
                        array(
                              'var' => 'source',
                              'compare' => 'regex',
                              'value' => '(200|300)+'
                              ),
                        array(
                              'relation' => 'OR',
                                array(
                                      'var' => 'age',
                                      'compare' => '=',
                                      'value' => '59'
                                      ),
                                array(
                                      'var' => 'age',
                                      'compare' => '=',
                                      'value' => '60'
                                      )
                                      )
                      ),
                array(
                        'relation' => 'or',
                        array(
                              'var' => 'age',
                              'compare' => '<',
                              'value' => '10'                                 
                              ),
                        array(
                              'var' => 'age',
                              'compare' => '>=',
                              'value' => '60'
                              )
                      ),
                     array(
                              'var' => 'source',
                              'compare' => '=',
                              'value' => '300'
                              ),

                );


function evaluateConditions($condArray, $varablesArray){

if(!$condArray || !is_array($condArray)){throw new Exception('Missing Conditions Input Array');}
if(!$varablesArray || !is_array($varablesArray)){throw new Exception('Missing Variables Input Array');}

//PULL VARIABLES FROM ARRAY
foreach($varablesArray as $key_var => $value_var){
    ${$key_var} = $value_var;
}


///PROCESS THE ARRAY THAT CONTAINS THE COMPARISON ARRAY
if (!$condArray['relation']){

 //FORMAT COMPARE INPUT
 $condArray['compare'] = strtoupper(trim($condArray['compare']));
 $condArray['compare'] = preg_replace('/^=$/','==',$condArray['compare']);

 ///ACCEPTED COMPARE VALUES
 $accepted_compare_array = array('=','==','===','<>','!=','!==','>','>=','<','<=','REGEX');

 //VERIFY REQUIRED FIELDS ARE PRESENT
 if(!$condArray['var']){throw new Exception('Missing var');}
 if(!$condArray['compare']){throw new Exception('Missing compare');}
 if(!$condArray['value']){throw new Exception('Missing value');}

 //VERIFY ALL VALUES
 if($condArray['compare'] != 'REGEX' && !is_numeric($condArray['value'])){throw new Exception('Value is Not Numeric');}
 if(!in_array($condArray['compare'], $accepted_compare_array)){throw new Exception('Invalid Compare Value');}
 if(!preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/",$condArray['var'])){throw new Exception('Invalid Var');}

 if($condArray['compare'] == 'REGEX'){
    $condArray['compare'] = preg_replace('/\//','\/',$condArray['compare']);
    $eval_str = 'if(preg_match("/'.$condArray['value'].'/i", $'.$condArray['var'].')){return 1;} else{return 0;}'; 
 }
 else{   
    $eval_str = 'if($'.$condArray['var'].' '.$condArray['compare'].' '.$condArray['value'].'){return 1;} else{return 0;}';
 }

 return eval($eval_str);

 }
else{

 $condArray['relation'] = strtoupper(trim($condArray['relation']));

 //VERIFY RELATION VALUE
 $accepted_relation_array = array('AND','OR');
 if(!in_array($condArray['relation'], $accepted_relation_array)){throw new Exception('Relation Invalid');}

 //VERIFY THAT AT LEAST TWO ARRAYS
 $array_count = 0;
 foreach($condArray as $condArray_var){
    if(is_array($condArray_var)){$array_count++;} 
 }

 if($array_count < 2){throw new Exception('Missing Comparison Array');}

 }



if (strtoupper($condArray['relation']) == 'OR') {
 unset($condArray['relation']);

 $eval_str = 'if(';
 for($i=0; $i < count($condArray); $i++){
    $eval_str .= evaluateConditions($condArray[$i], $varablesArray);
    if($i != count($condArray)-1){$eval_str .= ' || ';}  
 }   
 $eval_str .= '){return 1;}else{return 0;}';

 return eval($eval_str);

 }
 if (strtoupper($condArray['relation']) == 'AND'){
 unset($condArray['relation']);
 $eval_str = 'if(';
 for($i=0; $i < count($condArray); $i++){
    $eval_str .= evaluateConditions($condArray[$i], $varablesArray);
    if($i != count($condArray)-1){$eval_str .= ' && ';}  
 }   
 $eval_str .= '){return 1;}else{return 0;}';

 return eval($eval_str);

 }
throw new Exception('General Error Occurred');
} //end of function

/////

try {
echo evaluateConditions($conditions, $input_variables);
} 
catch (Exception $e) {
echo 'Caught exception: ',  $e->getMessage(), "\n";
}   
4

1 回答 1

5

处理这个问题的最简单方法是使用 PHP 的 eval() 方法(http://php.net/manual/en/function.eval.php)进行递归:

static function evaluateArray($inArray)
{
  if (!$inArray['relation']) return eval($inArray['var'] + $inArray['compare'] + $inArray['value']);
  if ($inArray['relation'] == 'OR') return eval(evaluateArray($inArray[0])+'||'+evaluateArray($inArray[1]));
  if ($inArray['relation'] == 'AND') return eval(evaluateArray($inArray[0])+'&&'+evaluateArray($inArray[1]));
  return false; //could throw exception here if you wanted
}

这旨在与字符​​串一起使用,但可以轻松修改。此外,您可能应该检查以确保每个子数组的结构正确,但我已经忽略了这段代码。

于 2012-09-05T03:50:12.980 回答