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

Ann*_*sai 6 php laravel

我想分别对tot_Priceunit_Price求和,以便我可以分析这两个属性的平均值。

\n\n
<tr>\n    <td>{{ $X_land->house_Type }}</td>\n    <td class="address">{{ $X_land->the_Location }}</td>\n    <td>{{ $X_land->tot_Price }}</td>\n    <td>{{ $X_land->tran_Area }}</td>\n    <td>{{ $X_land->unit_Price }}</td>\n    <td><button id="opener<?php echo $opencount?>">\xe8\xa9\xb3\xe7\xb4\xb0\xe8\xb3\x87\xe8\xa8\x8a</button></td>\n</tr>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我该怎么做?
\n谢谢。

\n

xmh*_*fiz 10

sum您可以为tot_Priceand添加变量unit_Price并在 foreach 循环中添加

\n\n
<?php $sum_tot_Price = 0 ?>\n<?php $sum_unit_Price = 0 ?>\n@foreach ($yourData as X_land)\n<tr>\n    <td>{{ $X_land->house_Type }}</td>\n    <td class="address">{{ $X_land->the_Location }}</td>\n    <td>{{ $X_land->tot_Price }}</td>\n    <td>{{ $X_land->tran_Area }}</td>\n    <td>{{ $X_land->unit_Price }}</td>\n    <td><button id="opener<?php echo $opencount?>">\xe8\xa9\xb3\xe7\xb4\xb0\xe8\xb3\x87\xe8\xa8\x8a</button></td>\n</tr>\n<?php $sum_tot_Price += $X_land->tot_Price ?>\n<?php $sum_unit_Price += $X_land->unit_Price ?>\n@endforeach\n\n<tr>\n    <td>Sum tot_Price {{ $sum_tot_Price}}</td>\n    <td>Sum unit_Price {{ $sum_unit_Price}}</td>\n</tr>\n
Run Code Online (Sandbox Code Playgroud)\n


Kma*_*rYC 5

认为:

\n\n
@foreach($lands as $X_land)\n<tr>\n    <td>{{ $X_land->house_Type }}</td>\n    <td class="address">{{ $X_land->the_Location }}</td>\n    <td>{{ $X_land->tot_Price }}</td>\n    <td>{{ $X_land->tran_Area }}</td>\n    <td>{{ $X_land->unit_Price }}</td>\n    <td><button id="opener<?php echo $opencount?>">\xe8\xa9\xb3\xe7\xb4\xb0\xe8\xb3\x87\xe8\xa8\x8a</button></td>\n</tr>\n@endforeach\n
Run Code Online (Sandbox Code Playgroud)\n\n

你可以这样得到总计:

\n\n
{{$lands->sum(\'tot_Price\')}}\n{{$lands->sum(\'unit_Price\')}}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者你可以获得平均值:

\n\n
{{$lands->avg(\'tot_Price\')}}\n{{$lands->avg(\'unit_Price\')}}\n
Run Code Online (Sandbox Code Playgroud)\n