简体   繁体   中英

loop date insert x times php

I am trying to put together some code in PHP so that after I add a date, the next x number dates are added.

Without going into specifics, the general idea is that after a customer has been visited, the visit date will be entered, this then triggers this code, to add the next x visit dates in (the visits will be every 6 months), but depending on the customer there may be 3, 4 or 5 visits, I have this set as a $value and am good with that and being able to calculate future dates.

What I dont know is how to loop the insert, so if

$value = 4, then
n1, initial date + 6 months
n2, initial date + (6*2) months
n3, initial date + (6*3) months
n4, initial date + (6*4) months - yes i know i could just add 6 months to n-1, but trying to keep it simple.

I have never worked with nth term approach in a loop and wondered if someone could a) point me in the direction of a related article, and b) give me an example.

Basically what I want to do is LOOP it x times ($value = x), and then in each loop be able to use 6 * x.

Thanks

Using the DateTime object and the DateInterval Object this can be done quite simply using a for loop.

$frequency = 6;    // could be 6 or 12 months, set elsewhere in your code

$visit_count = 5; //for this example
$initial_date = new DateTime($value["VisitDate"]);  // last visit date

$interval = new DateInterval("P$frequencyM");    // visit every $frequency  months

for ( $i=0; $i < $visit_count; $i++ ) {
    $visits[] = clone $initial_date->add($interval);
}
print_r($visits);

RESULT

Array
(
    [0] => DateTime Object
        (
            [date] => 2023-01-01 00:00:00.000000
            [timezone_type] => 3
            [timezone] => UTC
        )

    [1] => DateTime Object
        (
            [date] => 2023-07-01 00:00:00.000000
            [timezone_type] => 3
            [timezone] => UTC
        )

    [2] => DateTime Object
        (
            [date] => 2024-01-01 00:00:00.000000
            [timezone_type] => 3
            [timezone] => UTC
        )

    [3] => DateTime Object
        (
            [date] => 2024-07-01 00:00:00.000000
            [timezone_type] => 3
            [timezone] => UTC
        )

    [4] => DateTime Object
        (
            [date] => 2025-01-01 00:00:00.000000
            [timezone_type] => 3
            [timezone] => UTC
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM