简体   繁体   English

在 [php] 中的 foreach 循环中求和值

[英]Sum values in foreach loop in [php]

I want to sum tot_Price and unit_Price respectively so that I can analyze the average of these two attributes.我想分别对tot_Priceunit_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>

How should I do this?我该怎么做?
Thanks.谢谢。

You could add sum variable for both tot_Price and unit_Price and add in foreach loop您可以为tot_Priceunit_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>

Assume:认为:

@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

You can get total like this:你可以像这样得到总数:

{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}

Or you can get average:或者你可以得到平均值:

{{$lands->avg('tot_Price')}}
{{$lands->avg('unit_Price')}}

To be very simple,很简单,

You need to focus on the @foreach loop first,您需要首先关注@foreach循环,
eg @foreach($people as $person)例如@foreach($people as $person)

and there is the salary which you can access in foreach , Through $person->salary并且您可以通过$person->salary salary foreach中访问薪水

If you want to calculate the sum of salaries then use a simple sum like this,如果您想计算工资总和,请使用这样的简单总和,

$people->sum('salary') , Remember not use $person $people->sum('salary') ,记住不要使用$person

In your case在你的情况下
{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM