我正在创建一个动态编码的if语句,它是基于站点访问者提交的值构建的。if语句代码内置到$if_statement变量中,如下所示:
$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循环中解析一个非常大的XML文件,因此我希望在执行foreach循环之前对if语句进行动态编码。由于if语句中可以测试1到9个条件(取决于有多少GET方法从用户输入中生成空变量),因此系统只测试一次空变量(在foreach循环执行之前)似乎比在foreach循环的每个循环中测试空变量要困难得多。当只需要测试1或2个条件时,对9种条件进行测试是一种浪费。
但是显然是因为$if_statement是在foreach循环执行之前构建的,这导致动态if语句代码的“Product”部分不被计算。因此,在下面的foreach循环中没有显示任何内容:
$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product as $Product) {
if ($if_statement) { // the problem lies here
echo $Product->name;
}}是否有一种方法来构建动态创建的if语句,该语句在foreach循环执行之前解析XML?
发布于 2014-04-09 01:02:23
不,如果您依赖于$Product变量,则在访问它之前不能基于它创建语句。这应该很简单。
if($Product->something) {} //this is meaningless and will throw and error
//if you define $Product->something here你只需要在循环中做你的if_statement并且开销是可以忽略的.
https://stackoverflow.com/questions/22950107
复制相似问题