2017-01-17 137 views
1

我有一个在db中有许多约会的客户列表。我想遍历每个客户的总计约会时间,以便我可以创建发票。当我运行下面的代码时,第一个客户端的约会持续时间被正确添加。然而,我的问题是,对于下一个客户来说,它似乎也增加了第一个客户持续时间。 array_sum是正确的方法吗?如果不是,我需要使用什么?在Laravel PHP的每个foreach循环中增加array_sum的总和。

foreach($clients as $client) 
     { 
      $appointments = Client::find($client->id)->appointments()->get(); 

       foreach($appointments as $appointment) 
       { 

        $date1  = $appointment->starts_at; 
        $date2  = $appointment->ends_at;       
        $start  = Carbon::parse($date1); 
        $end  = Carbon::parse($date2); 

        $length  = $start->diffinhours($end); 
        $duration[] = $length;   //is this correct? 
        $total = array_sum($duration); //is this correct? 
       } 

      $invoice     = new Invoice; 
      $invoice->total_hours  = $total; 
      dd($invoice); 
      $invoice->save(); 
     } 
+0

每个循环后需要重置总和。我的意思是就在第二个foreach循环代码之前(在获得'$ appointmentments'之后)使得总变量为0,即'$ total = 0' – webDev

回答

1

是的,你可以用这个方法,但是你需要把它移到循环外,你也应该清空$total与每次迭代:

.... 
$duration = []; 

foreach ($appointments as $appointment) 
{ 
    $date1  = $appointment->starts_at; 
    $date2  = $appointment->ends_at;       
    $start  = Carbon::parse($date1); 
    $end  = Carbon::parse($date2); 

    $length  = $start->diffinhours($end); 
    $duration[] = $length; 
} 

$total = array_sum($duration); 
.... 

此外,您还可以添加start_atend_at时间戳the $dates array in a model并使用此代码代替:

foreach ($appointments as $appointment) 
{ 
    $duration[] = $appointment->starts_at->diffInHours($appointment->ends_at); 
} 
+1

谢谢你。有用。我也实施了关于$日期的建议。 –

2

重置为每个客户端,并任命循环之后的持续时间array_sum

foreach ($clients as $client) 
{ 
    $appointments = Client::find($client->id)->appointments()->get(); 

    $duration = array(); 

    foreach ($appointments as $appointment) 
    { 
     $date1  = $appointment->starts_at; 
     $date2  = $appointment->ends_at;       
     $start  = Carbon::parse($date1); 
     $end  = Carbon::parse($date2); 

     $length  = $start->diffinhours($end); 
     $duration[] = $length; 
    } 

    $total = array_sum($duration); 

    $invoice     = new Invoice; 
    $invoice->total_hours  = $total; 
    dd($invoice); 
    $invoice->save(); 
} 
+0

感谢你的这一点。有用。 –