1

I have the following code that works perfect with a pre-formatted DateTime array:

foreach ($ranges as $range) {
    while ($range['start'] <= $range['end']) {
        $date = $range['start']->format('Y-m-d');
        $dates[$date] = (isset($dates[$date]) ? $dates[$date] : 0) + 1; 1;//define new $dates array
        $range['start']->modify('+1 day');
    }
}

$sold_out = array_filter($dates, function($n) { return $n >= 7; });

echo implode(',', array_keys($sold_out));

But, my production array is not "pre-formatted" as DateTime

In the linked Fiddle you can see we are linking to a native array where the values are 'strings' http://phpfiddle.org/main/code/zni4-enk5

This produces an 'Exception: Call to a member function format() on string'
on the line where we step through the dates:
$range['start']->modify('+1 day');

To test change the array target from $ranges to $ranges2:
Example: foreach ($ranges2 as $range) {

Is the problem not properly being able to set the values as DateTime?

GOAL: Output comma delimited dates that share a date that intersects x number of times within the provided date ranges.

1 Answer 1

2

You may use DateTime's createFromFormat() to convert these values to DateTime values.

DateTime::createFromFormat('Y-m-d', '2019-02-18');

foreach ($ranges2 as $range) {
    $range['start'] = DateTime::createFromFormat('Y-m-d', $range['start']);
    $range['end'] = DateTime::createFromFormat('Y-m-d', $range['end']);
    while ($range['start'] <= $range['end']) {
        $date = $range['start']->format('Y-m-d');
        $dates[$date] = (isset($dates[$date]) ? $dates[$date] : 0) + 1; 1;//define new $dates array
        $range['start']->modify('+1 day');
    }
}

Hope this helps,

Sign up to request clarification or add additional context in comments.

1 Comment

Remember we are dealing with variables and not able to change the native array where each date is a String ($ranges2 = array(...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.