[英]Sum values in foreach loop in [php]
我想分别对tot_Price
和unit_Price
求和,以便分析这两个属性的平均值。
<tr>
<td>{{ $X_land->house_Type }}</td>
<td class="address">{{ $X_land->the_Location }}</td>
<td>{{ $X_land->tot_Price }}</td>
<td>{{ $X_land->tran_Area }}</td>
<td>{{ $X_land->unit_Price }}</td>
<td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
我该怎么做?
谢谢。
您可以为tot_Price
和unit_Price
添加sum
变量并添加到 foreach 循环中
<?php $sum_tot_Price = 0 ?>
<?php $sum_unit_Price = 0 ?>
@foreach ($yourData as X_land)
<tr>
<td>{{ $X_land->house_Type }}</td>
<td class="address">{{ $X_land->the_Location }}</td>
<td>{{ $X_land->tot_Price }}</td>
<td>{{ $X_land->tran_Area }}</td>
<td>{{ $X_land->unit_Price }}</td>
<td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
<?php $sum_tot_Price += $X_land->tot_Price ?>
<?php $sum_unit_Price += $X_land->unit_Price ?>
@endforeach
<tr>
<td>Sum tot_Price {{ $sum_tot_Price}}</td>
<td>Sum unit_Price {{ $sum_unit_Price}}</td>
</tr>
认为:
@foreach($lands as $X_land)
<tr>
<td>{{ $X_land->house_Type }}</td>
<td class="address">{{ $X_land->the_Location }}</td>
<td>{{ $X_land->tot_Price }}</td>
<td>{{ $X_land->tran_Area }}</td>
<td>{{ $X_land->unit_Price }}</td>
<td><button id="opener<?php echo $opencount?>">詳細資訊</button></td>
</tr>
@endforeach
你可以像这样得到总数:
{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}
或者你可以得到平均值:
{{$lands->avg('tot_Price')}}
{{$lands->avg('unit_Price')}}
很简单,
您需要首先关注@foreach
循环,
例如@foreach($people as $person)
并且您可以通过$person->salary
salary
foreach
中访问薪水
如果您想计算工资总和,请使用这样的简单总和,
$people->sum('salary')
,记住不要使用$person
在你的情况下{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.