在Laravel PHP的每个foreach循环中使array_sum添加总计。

时间:2017-01-17 20:52:16

标签: php laravel laravel-5.3

我有一个在db中有很多约会的客户列表。我想迭代总计每个客户的持续时间的约会,这样我就可以创建发票。当我运行以下代码时,正确添加第一个客户的约会持续时间。但是我的问题是,对于下一个客户端,它似乎也添加了第一个客户端持续时间。 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();   
        }

2 个答案:

答案 0 :(得分: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();   
}

答案 1 :(得分: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);
}