将Looped DateTime值拉到数组

时间:2018-01-31 01:00:21

标签: php arrays datetime

我有以下代码,其中$ Clinics是一个多维对象数组,格式如下:

Array
(
    [0] => Clinics Object
        (
            [PlanID] => 1
            [id] => 1
            [ClinicCode] => X123ABCD1
            [ClinicDesc] => Test Description
            [SchDay] => Monday
            [SchWeek] => 
            [SchWeekBetween] => 1
        )

    [158] => Clinics Object
        (
            [PlanID] => 1
            [id] => 159
            [ClinicCode] => Y234BCDE2
            [ClinicDesc] => Test Description
            [SchDay] => Monday
            [SchWeek] => 
            [SchWeekBetween] => 1
        )
)

我使用下面的代码循环遍历每个对象,从每周一天的预定日(SchDay)开始,如果SchDay是每天,则每天开始。

$StartDate = new DateTimeImmutable("2018-04-01");
$EndDate = new DateTimeImmutable("2019-03-31");
$Output = array();

foreach ($Clinics as $Clinic) {

    // Set First Date of loop period
    if ($Clinic->SchDay == "Daily") {
        $ClinicStartDate = $StartDate->format("d-m-Y");
        $SchCount = "+1 day"; 
    } else {
        $ClinicStartDate = "First ".$Clinic->SchDay." of ".$StartDate->format("F Y");
        $SchCount = "+7 days";
    }

    // Loop through Dates and add to array
    for($i = new DateTime($ClinicStartDate); $i <= $EndDate; $i->modify($SchCount)){

        $Clinic->Date = $i;
        $Output[] = $Clinic;    
    } 
};

print_r($Output);

我遇到的问题是,当我打印数组时,每个诊所迭代的Date值都是相同的 - 循环的最后一个日期,并且数组不会按照for循环捕获每个DateTime。我想我明白为什么会这样做,但我无法弄清楚如何绕过它。

2 个答案:

答案 0 :(得分:0)

循环仅对对象实例化一次。然后,您将在每次迭代时修改对象,然后将其引用分配给数组。所有作业都引用同一个对象。

很容易解决这个问题,但你必须为每个作业实例化一个新的日期时间:

for ($i = new DateTime("2018-05-01"); $i <= $EndDate; $i->modify('+7 days')) {
    $Clinic->Date = new DateTime($i->format("Y-m-d"));
    $Output[] = $Clinic;
}

http://php.net/manual/en/language.oop5.references.php

编辑: 这是一个有效的例子。您所要做的就是复制粘贴以查看它的实际效果。

<?php

$StartDate = new DateTimeImmutable("2018-04-01");
$EndDate = new DateTimeImmutable("2019-03-31");
$Output = array();

for ($i = new DateTime("2018-05-01"); $i <= $EndDate; $i->modify('+7 days')) {
    $Output[] = new DateTime($i->format("Y-m-d"));
}

var_dump($Output);

答案 1 :(得分:0)

管理以获得具有以下内容的所需输出:

class ItemInline(admin.TabularInline):
    model = Item
    formset = ItemInlineFormset

class ItemInlineFormset(forms.models.BaseInlineFormSet):
    def clean(self):
        super(ItemInlineFormset, self).clean()
        for form in self.forms:
            if form.instance.some_condition:
                form.add_error('some_condition', 'Nope')