php一个简单的数学任务

Dom*_*s55 1 php arrays

我有最简单的数学问题,我无法弄明白(可能整天都在工作累了).这很简单,我循环浏览项目并希望显示最终价格而不需要税等等.问题是我的数学是正确的,但是当我显示价格时,所有项目都具有相同的值(值最后一项).据我所知,每次循环时总变量都在变化,最后一个循环显示最后一个值.如何解决?

public function getTotal($items)
{
    $total;
    foreach($items as $item){
        $total = $item->getPrice() - $item->getDiscount() + $item->getValue();
    }
    return $total;
}
Run Code Online (Sandbox Code Playgroud)

它应该显示:

Item1: 154
Item2: 77
Run Code Online (Sandbox Code Playgroud)

它显示:

Item1:77
Item2:77
Run Code Online (Sandbox Code Playgroud)

Rai*_*ent 6

你在每次迭代时都会覆盖整个变量.试试以下内容:

public function getTotal($items)
{
$total = 0;
foreach($items as $item){
    $total += $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
Run Code Online (Sandbox Code Playgroud)

编辑:我知道您希望看到每个产品的总数.你可以做的是返回一个数组而不是一个数组.例如这样:

public function getTotal($items)
{
    $total = array();
    foreach($items as $item){
        $total[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
    }
    return $total;
}
Run Code Online (Sandbox Code Playgroud)