2017-04-03 99 views
1

我正在尋找一種方法來計算laravel中數據庫的累積值。計算laravel中的累積值

目前我檢索一組值,每天一個。我希望能夠在頁面上顯示累計值。我想是這樣的

enter image description here

代碼在我的控制器是: enter image description here

在這裏,我retreive製造和安裝的值從形式。我想計算累計製造和每天勃起值...

+1

發表您的代碼! –

+0

我編輯了這個問題..可以ü請檢查它 –

+0

將您的代碼發佈爲代碼而不是圖像 – apokryfos

回答

2

你可以簡單的做到這一點的看法:

<?php $cumulative = 0; ?> 

@foreach ($collection as $object) 
    <?php $cumulative += $object->value; ?> 
    {{ $object->value }} | {{ $cumulative }} 
@endforeach 
+0

好的建議 –

+0

這樣的邏輯不應該在視圖上完成,它應該至少在控制器上完成並通過視圖,這意味着你也可以使用$ collection-> each(function(){})格式。 – James

+0

@詹姆斯爲什麼不呢?這是一個簡單的迭代。當然,您可以在將數據傳遞給視圖之前準備數據,但是我不會那麼做這樣簡單的操作。 –

1

創建功能,並按照與

public function CumulativeCalculator($accounts){ 

    $driverAccounts  = []; 
    $cumulativePayments = 0; 
    foreach($accounts as $account){ 

     $cumulativePayments += $account->value; 
     $currentDriverAccounts = []; 
     $currentDriverAccounts['id'] = $account->id; 
     $currentDriverAccounts['realValue'] = $account->value; 
     $currentDriverAccounts['cumulativeValue'] = $cumulativePayments; 
     array_push($driverAccounts,$currentDriverAccounts); 
    } 
    return $driverAccounts; 

} 

在你的視圖中這樣做

<table class="table table-hover table-striped"> 
<thead> 
    <th>Values</th> 
    <th>Cumulative Values</th> 
</thead> 
<tbody> 
    @foreach($driverAccounts as $dataValue) 
     <tr> 
      <td>{{$dataValue['realValue']}}</td> 
      <td>{{$dataValue['cumulativeValue']}}</td> 
     </tr> 
    @endforeach 
</tbody> 

這將爲你工作,對不起我在匆忙但它會奏效。