在Laravel工作,我对操作有点困惑。我有2列 count_all 和 price_unit ,我正在尝试将它们的值相乘,然后将它们相加。我试图这样做:
@foreach($materials as $material)
{{$sum += $material->price_unit * $material->count_all}}
@endforeach
但它返回错误:
Undefined variable: sum
答案 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}}