Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values in foreach loop in [php]

Tags:

php

laravel

I want to sum tot_Price and unit_Price respectively so that I can analyze the average of these two attributes.

<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.

like image 515
Annie Tsai Avatar asked Feb 07 '23 07:02

Annie Tsai


1 Answers

You could add sum variable for both tot_Price and unit_Price and add in foreach loop

<?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>
like image 140
xmhafiz Avatar answered Feb 16 '23 18:02

xmhafiz