我从XMl获得一些奖励并想要计算总和。为什么不是$M_commission
166.63的输出?
$i = 0;
$commission_trans = 0;
foreach($responseXml->lead as $lead)
{
if ($i == 0) {
$last_trans = $lead->leadTime;
}
$commission_trans = $commission_trans + $lead->reward;
echo $lead->reward;
echo "\n";
$i++;
}
$M_lastclick = $last_trans;
$M_commission = number_format($commission_trans, 2);
echo $M_commission;
echo "\n";
echo $M_lastclick;
输出: 100.0 0.63 3.0 30.0 3.0 30.0 166.00 2013-05-10T13:42:01.058 + 02:00
我试过
$commission_trans = number_format($commission_trans + $lead->reward, 2);
但输出相同。
Tnx很多!
答案 0 :(得分:1)
“XML”表示,这来自某些XML流(simple_xml?):
foreach($responseXml->lead as $lead)
因此,对象成员($lead->reward
)是字符串,而不是浮点数。
$commission_trans
初始化为普通零,因此它是一个整数。
这一行$commission_trans = $commission_trans + $lead->reward;
给出了:
(int) = (int) + (string);
我会尝试将XML字符串显式转换为float:
$i = 0;
$commission_trans = 0.0;
foreach($responseXml->lead as $lead)
{
if ($i == 0) {
$last_trans = $lead->leadTime;
}
$commission_trans += floatval($lead->reward);
// or (float)$lead->reward;
echo $lead->reward;
echo "\n";
$i++;
}
答案 1 :(得分:1)
我认为标记$first
优于$i++
。
$first = true;
$commission_trans = 0.0;
foreach($responseXml->lead as $lead) {
if ($first) {
$last_trans = (float)$lead->leadTime;
$first = false;
}
$commission_trans += (float)$lead->reward;
echo $lead->reward.PHP_EOL;
}
$M_lastclick = $last_trans;
$M_commission = number_format($commission_trans, 2);
echo $M_commission.PHP_EOL;
echo $M_lastclick;
对Ideone进行测试:http://ideone.com/1pi7mQ