首页 > 解决方案 > IF 条件中的 foreach 不会输出,即使条件为 TRUE

问题描述

我已经看了太久了,无法辨别为什么它不起作用。如示例文件的注释中所述(下面的链接),我可以为 IF 条件中使用的变量输出正确的值。但是,只要我将 foreach 包装在条件中,然后是 ELSE,就会忽略该条件并输出 ELSE 语句。

我已经测试了这个用数字替换两个 IF 变量中的一个/两个。在这种情况下它可以正常工作。但是当它是两个变量时,它不会。我很困惑,并确信它是完全基本且可能的语法,我对此视而不见,因为我试图找到它太多次了……我希望如此。

PHP: https://pastebin.com/2ZGTPjs0

$xml = simplexml_load_file('file.xml');

$expenseCount = $xml->EXP->count();
$grandTotal = $xml->GRANDTOTAL;
$annualMax = $xml->ANNUALMAX;

// xPath is correct. The below test outputs the correct numbers.
// echo "<h1>GRAND TOTAL: ".$grandTotal."</h1><br/><h1>ANNUAL MAX: ".$annualMax."</h1>";

// The below if condition seems to be ignored and I can't figure out why!!
// Even though $grandTotal IS GREATER THAN $annualMax, the else statement
if ($grandTotal > $annualMax) {

foreach($xml->EXP as $expenses) {

echo "<div class=\"coupon ".$i."\">";
echo "<h1>Reimbursement</h1><h2>Coupon No. ".$i." of ".$expenseCount."</h2>";

echo "<table>
<tbody>
<tr class=\"headings\">
<th>Service</th>
<th>Vendor</th>
<th>Date of Service</th>
<th>Reason</th>
<th>Total Cost</th>
<th>Amount Paid</th>
<th>Balance Due</th>
</tr>";
echo "<tr class=\"expense-details\">";
echo "<td>".$expenses->SERVICE."</td>";
echo "<td>".$expenses->VENDOR."</td>";
$serviceDate = date('M d, Y', strtotime($expenses->DATE));
echo "<td>".$serviceDate."</td>";
echo "<td>".$expenses->REASON."</td>";
echo "<td>$".$expenses->COST."</td>";
echo "<td>$".$expenses->PAID."</td>";
echo "<td>$".$expenses->BALANCE."</td>";
echo "</tr>
</tbody>
</table>";

echo "</div>";

$i++;
}
} else {
echo "<div class=\"not-yet\">";
echo "<h1>Your current total is $".$grandTotal.". You have not exceeded the annual minimum out-of-pocket expenses of $".$annualMax.".</h1>";
echo "</div>";
}

XML:https ://pastebin.com/3Md8w93J

<EXPREP>
<GRANDTOTAL>727.94</GRANDTOTAL>
<ANNUALMAX>714</ANNUALMAX>
<EXP>
<DATE>Fri Jan 12 2018 00:00:00 GMT-0500 (EST)</DATE>
<SERVICE>Repair</SERVICE>
<VENDOR>ABC Auto Body</VENDOR>
<REASON>Out of Alignment</REASON>
<COST>130</COST>
<PAID>110</PAID>
<BALANCE>20</BALANCE>
</EXP>
<EXP>
<DATE>Tue Jan 23 2018 00:00:00 GMT-0500 (EST)</DATE>
<SERVICE>Repair</SERVICE>
<VENDOR>XYZ Gas Station</VENDOR>
<REASON>Travel Gas</REASON>
<COST>212</COST>
<PAID>192</PAID>
<BALANCE>20</BALANCE>
</EXP>
<EXP>
<DATE>Tue Jan 23 2018 00:00:00 GMT-0500 (EST)</DATE>
<SERVICE>Radiator Flush</SERVICE>
<VENDOR>Quick Flush</VENDOR>
<REASON>Annual Radiator Maintenance</REASON>
<COST>101.12</COST>
<PAID>91.12</PAID>
<BALANCE>10</BALANCE>
</EXP>
<EXP>
<DATE>Fri Jan 26 2018 00:00:00 GMT-0500 (EST)</DATE>
<SERVICE>Oil Change</SERVICE>
<VENDOR>ABC Auto Body</VENDOR>
<REASON>3000 Mile Oil Change</REASON>
<COST>125</COST>
<PAID>105</PAID>
<BALANCE>20</BALANCE>
</EXP>
</EXPREP>

Pastebins 可以使用一周。

标签: phpxmlif-statementforeachconditional-statements

解决方案


尝试将变量转换为浮点数。就目前而言,它们是 SimpleXML 对象,可能会打乱您的比较:

$grandTotal = (float) $xml->GRANDTOTAL; $annualMax = (float) $xml->ANNUALMAX;


推荐阅读