简体   繁体   中英

PHP Query/Comparison Method with Operators

My PHP page has a range of variables on each load; their values determine what widgets are displayed. Each widget has set criteria for when it should display.

Example. Display widget 'A' where:

"page==1, page!=3, user>9, rank!=blue"

$myVars = array();
$myVars['page'] = 1;
$myVars['user'] = 99;
$myVars['rank'] = 'red';

In this scenario I've written a simple method - it delimits the query and does a comparison on each criteria and stops as soon as a FALSE is encountered. The problem is there are no "OR" operators supported by my engine. Every criteria must be met. And I cannot get my head around how the operators could be added to it.

"page==1 || page==2 && page!=3 && user>9 || user==3 && rank !=blue"

This would give me much more flexibility on when a widget would display, without making lots of duplicate widgets for different scenarios. I see a parallel between how SQL must run queries and how I want to query my variables - is there a prewritten engine I can use or is my fate set in to writing a complete engine to work out if a widget has met criteria?

Thanks in advance, Craig.

Extend your language to support Conjunctive Normal Form or Disjunctive Normal Form

page==1 || page==2 && page!=3 && user>9 || user==3 && rank !=blue

Will look like (CNF):

(page==1 || page==2) && page!=3 && (user>9 || user==3) && rank !=blue

If you want to make parsing simpler you can do:

(page==1 || page==2) && (page!=3) && (user>9 || user==3) && (rank !=blue)

DNF would look like:

(page==1 && page!=3 && user>9 && rank!=blue)
||
(page==2 && page!=3 && user>9 && rank!=blue)
||
(page==1 && page!=3 && user==3 && rank!=blue)
||
(page==2 && page!=3 && user==3 && rank!=blue)

CNF seems more natural here.

另一个可行的解决方案(比eval更安全)可能是使用parse_str的某种组合将动态变量转换为可比较的变量-但是我不确定如何在没有eval的情况下仍然可以生成动态if语句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM