即使条件为TRUE,也不会输出IF条件内的foreach

时间:2018-04-24 20:53:27

标签: php xml if-statement foreach conditional-statements

我已经看了太长时间才能辨别出它为什么不能正常工作。如示例文件的注释(下面的链接)中所述,我可以输出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已经用了一个星期了。

1 个答案:

答案 0 :(得分:0)

尝试将变量转换为float。就目前而言,它们是SimpleXML对象,可能会搞砸你的比较:

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