duanhui3759 2011-12-13 16:59
浏览 48

匹配公式(SQL'ish)对PHP数组返回true或false

This is a tricky one to explain. I have an associative array which I want to run a set of rules against to return true or false.

I was wondering if there is a library somewhere allowing me to compare a rule (or set of) against an array. Almost like SQL exept I have the record, I just need to see if the SQL would return it or not.

For Example:

$subject = array('name' => 'John Smith', 'age' => '44');
$formula = "name LIKE 'John%' AND (age = 44 OR age = 45)";
if(match($formula, $subject))
return true;
else 
return false;

The subject array is NOT from a database it is actually from a form post, otherwise I would just run the SQL and if it returned the correct record then it would be true. Plus this is something that I would like to use a lot with may different associative arrays so adding to a table then running the query to get the same record back will not be possible either. Basically I can't use a database.

  • 写回答

3条回答 默认 最新

  • dongliao3450 2011-12-13 17:15
    关注

    If you want an expression to be parsed as if it were SQL, then use an SQL parser....

    $subject = array('name' => 'John Smith', 'age' => '44'); 
    $formula = "'name' LIKE 'John%' AND ('age' = '44' OR 'age' = '45')";
    $result=try_expression($subject, $formula);
    
    function try_db_expression($subject, $formula) 
    {
    $keys=array_keys($subject);
    $vals=array_values($subject);
    
    foreach ($keys as $k=>$v) {
       $keys[$k]='/\b' . mysql_real_escape_string($v) . '\b/i';
    }
    foreach ($vals as $k=>$v) {
       $vals[$k]=mysql_real_escape_string($v);
    }
    $test=preg_replace($keys, $vals, $subject);
    $res=mysql_query("SELECT ($test) AS evald");
    if ($r=mysql_fetch_assoc($res)) return $r['evald'];
    return false;
    }
    

    Basically I can't use a database

    Then you'll have to build your own parser (not really - you can use PHP's eval - but you'll need to map the LIKE operator to PHP function).

    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端