문제

I am creating a dynamically coded if statement which is built based on values submitted from site visitors. The if statement code is built into the $if_statement variable, like this:

$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.

This if statement code will be used to parse a very large XML file in a foreach loop, so I would like the if statement to be dynamically coded PRIOR to the foreach loop executing. Since there can be anywhere between 1 to 9 conditions tested in the if statement (depending on how many GET methods produce empty variables from user input), it would seem less strenuous on the system to test for empty variables only once (prior to the foreach loop executing) than it would be to test for empty variables during EVERY loop of the foreach loop. Testing for 9 conditions when only 1 or 2 conditions need to be tested is a waste.

But apparently because the $if_statement is built PRIOR to the foreach loop executing, that is causing the 'Product->variable' portion of the dynamic if statement code to NOT be evaluated. So nothing is being displayed in the foreach loop below:

$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product as $Product) {

if ($if_statement) { // the problem lies here
echo $Product->name;
}}

Is there a way to build a dynamically created if statement that parses XML PRIOR to the foreach loop execution?

도움이 되었습니까?

해결책

No, if you depend on $Product variable, you cannot create a statement based on it before you access it. This should be pretty straightforward.

if($Product->something) {}  //this is meaningless and will throw and error
//if you define $Product->something here

you just have to do your if_statement in the loop and overhead is neglieable...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top