Annie Tsai Annie Tsai - 3 months ago 18
PHP Question

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.

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

Answer

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