在[php]的foreach循环中求和

6
我想分别对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>

我该怎么做呢?
谢谢。


只需使用一个临时的总容器,然后将这些值相加即可。 - Kevin
3个回答

10
您可以为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>

运行成功!感谢你的教程。 - Annie Tsai

5

假设:

@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')}}

嗨,我已经在我的项目中添加了分页方法。我遇到了一个问题,{{$lands->sum('tot_Price')}} 只会对当前页面的 tot_Price 进行求和,我该如何计算所有页面的 tot_Price 而不仅仅是一页?是否有在控制器中创建一些代码的解决方案?感谢您帮助我解决这个问题。 - Annie Tsai

1

非常简单,

首先需要关注@foreach循环,例如:@foreach($people as $person),在foreach中可以访问salary,通过$person->salary访问。

如果您想计算工资总和,可以使用简单的求和方法,例如:$people->sum('salary'),记得不要使用$person

在您的情况下
{{$lands->sum('tot_Price')}}
{{$lands->sum('unit_Price')}}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接