用Laravel增加for循环中的Php Carbon Date

时间:2015-11-27 22:08:26

标签: php laravel laravel-4 laravel-5 php-carbon

我尝试在for循环中增加carbon Date,如下所示

for($x = 0; $x < count($ms); $x++) {

    $msh = MaintenanceServiceNotifications::where('main_service_id', $ms[$x]->id)->where('status', 'done')->orderBy('created_at', 'desc')->first();

    if(Carbon::now() > $msh->created_at->addMinutes($ms[$x]->notification_period*2)) {

        for ($i = 0; $i < sizeof($customersNot)-1; $i++) {

            //here i need to get created_at and 30 minutes for it     
            $created_at[$i] = $msh->created_at->addMinutes($ms[$x]->notification_period);

            MaintenanceServiceNotifications::create([
                'main_service_id' => $ms[$x]->id,
                'user_id' => Auth::user()->id,
                'not_name' => 'some text',
                'created_at' => $created_at[$i]
            ]);
        }
    }
}

我需要在每个for循环中增加日期并将其传递给created_at 例如

第一个循环

2015-11-27 23:00:00然后creteat_at => 2015-11-27 23:00:00

第二个循环

2015-11-27 23:30:00然后created_at =>2015-11-27 23:30:00

任何建议,谢谢

3 个答案:

答案 0 :(得分:1)

试试这段代码:

$minutes = $ms[$x]->notification_period;
$dt = Carbon::createFromFormat('Y-m-d H:i:s', $msh->created_at);
$dt->addMinutes($minutes);
$create_at = $dt->toDateTimeString();

答案 1 :(得分:1)

我的建议有一些调整,

foreach ($ms as $m) {
    $msh = MaintenanceServiceNotifications::where('main_service_id', $m->id)->where('status', 'done')->latest()->first();

    if (Carbon::now() > $msh->created_at->addMinutes($m->notification_period*2)) {
        for ($i=0; $i<sizeof($customersNot)-1; $i++) {
            MaintenanceServiceNotifications::create([
                'main_service_id' => $m->id,
                'user_id' => Auth::user()->id,
                'not_name' => 'some text',
                'created_at' => $msh->created_at->addMinutes($m->notification_period * $i) // add 30*0, 30*1, 30*2 ...
            ]);
        }
    }
}

答案 2 :(得分:0)

我认为这可能是由于if语句永远不会给出,我建议进行简单的更改

if(Carbon::now()->gt( $msh->created_at->addMinutes($ms[$x]->notification_period*2)))

Carbon gt()函数检查日期是否大于给予函数的另一个日期。