乘以并添加列值

时间:2018-04-13 10:19:51

标签: php laravel loops

在Laravel工作,我对操作有点困惑。我有2列 count_all price_unit ,我正在尝试将它们的值相乘,然后将它们相加。我试图这样做:

@foreach($materials as $material)
    {{$sum += $material->price_unit * $material->count_all}}
@endforeach

但它返回错误:

Undefined variable: sum

2 个答案:

答案 0 :(得分:1)

$sum += $material->price_unit * $material->count_all表示$sum = $sum + $material->price_unit * $material->count_all。循环中第一次$sum未定义,因此您必须在循环外声明它

<?php $sum=0; ?>
@foreach($materials as $material)
    {{$sum += $material->price_unit * $material->count_all}}
@endforeach

答案 1 :(得分:-1)

尝试使用@php代替{{}}

首先声明$sum(在循环之外):@php($sum = 0)

然后@php($sum += $material->price_unit * $material->count_all)

如果要打印,请使用{{$sum}}