我有一道最简单的数学题要做,我只是想不通(可能是整天工作累了)。这很简单,我循环浏览项目并希望显示没有税费等的最终价格。问题是我的数学是正确的,但是当我显示价格时,所有项目都具有相同的值(最后一个项目的值)。我知道每次循环时总变量都在变化,并且在最后一个循环中显示最后一个值。如何解决?
public function getTotal($items)
{
$total;
foreach($items as $item){
$total = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
它应显示:
Item1: 154
Item2: 77
它显示:
Item1:77
Item2:77
您在每次迭代时都会覆盖总变量。请尝试以下操作:
public function getTotal($items)
{
$total = 0;
foreach($items as $item){
$total += $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
编辑:我知道您希望看到每个产品的总数。您可以做的是返回一个数组而不是双精度值。例如像这样:
public function getTotal($items)
{
$total = array();
foreach($items as $item){
$total[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
我不知道你的整个代码到底是什么,所以我有一些猜测,但你有没有考虑过使用这样的东西:
public function getTotal($item)
{
return $item->getPrice() - $item->getDiscount() + $item->getValue();
}
然后在您输出价格的方法中,您将拥有:
foreach( $items as $item )
{
// $item->getName() is an wild guess but still you get the point
echo $item->getName() . ': ' . $this->getTotal( $item );
}
另一种方法是将每个项目的总价存储在一个新数组中,然后将其返回:
public function getTotals($items)
{
$totals = array();
foreach( $items as $item )
{
$totals[ $item->getName() ] = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $totals;
}
然后你只需要:
$totals = $this->getTotals( $items );
foreach( $totals as $name => $totalPrice )
{
echo $name . ': ' . $totalPrice;
}
public function getTotal($items)
{
$total = array();
foreach($items as $key=>$item){
$total['Item'.$key] = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
您需要添加[]
它将返回一个数组列表,它应该是这样的
public function getTotal($items)
{
$total = array();
foreach($items as $item){
$total[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;// returns an array;
}
或者可以作为
public function getTotal($items)
{
$total = array();
foreach($items as $key => $item){
$total[$key] = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;// returns an array;
}