PHP - 创建一个动态编码的 if 语句



我正在尝试构建一个 if 语句,该语句根据访问该网站的用户提交的值动态编码。if 语句可能有 1 到 9 个条件进行测试(取决于用户输入),XML 值(来自 XML 文档)将根据 if 语句显示。

在 $if_语句变量中插入了潜在的 if 语句条件,如下所示:

$keyword = trim($_GET["Keyword"]);
if (!empty($keyword)) {
$if_statement = ($keyword == $Product->keyword);
}
$shopByStore = $_GET["store"];
if (!empty($shopByStore)) {
$if_statement = ($if_statement && $shopByStore == $Product->store);
}
// plus 7 more GET methods retrieving potential user input for the $if_statement variable.

但是,当使用动态编码的 if 语句时,下面的 foreach 循环中没有显示任何内容:

$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product as $Product) {
if ($if_statement) { // the problem lies here, because results ARE displayed when this if statement is removed
echo $Product->name;
}}

有什么建议吗?或者有没有更好的方法来动态编码 if 语句?

在运行时评估 $if_语句,然后再评估任何实际产品。您需要更改代码以在 foreach 循环期间传递产品,然后进行评估。

函数声明:

function if_statement($Product, $keyword=null, $store=null) {
    $if_statement=false;
    if($keyword)  $if_statement = ($keyword == $Product->keyword);
    if($store) $if_statement = $if_statement && ($shopByStore == $Product->store);
    return $if_statement;
}

功能评估

$keyword = trim($_GET["Keyword"]);
$shopByStore = $_GET["store"];
$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product as $Product) {
    if (if_statement($Product,$keyword, $store )) {
        echo $Product->name;
    }
}

顺便一提。看看PHP的原生filter_input。您正在评估用户输入而不进行清理。

$names = array('Keyword', 'store', ...);
$if_condition = true;
foreach ($names as $name) {
    if (isset($_GET[$name]))
        $if_condition = $if_condition && $_GET[$name] == $Product->$name;
}
if ($if_condition) {
...
}

最新更新