0

I am writing a PHP script where the inputs are:

From date
To date

I then want to take that date range and create an array of some sort that has:

Array(date,x)

As I add each date to the array, I will calculate the value that goes with it.

With .NET I would (off the top of my head) use a dictionary where the date was the key and x is the value.

The main task is getting that date range, then splitting that range into an array or dictionary of some sort (What would be ideal in php)

As i'm adding it to the array i'll run off some other code i've already wrote that calculate the value to go with that date

At the end of it all when it's added in there, i'll need to iterate through the array or list and add all the x values together.

2
  • 1
    You want to generate an array containing all the dates between your FROM date and TO date? Commented Feb 4, 2011 at 11:50
  • With any language I would (off the top of my head) run a loop... Commented Feb 4, 2011 at 11:53

3 Answers 3

7

(Untested)

function dateArray($from, $to, $value = NULL) {
    $begin = new DateTime($from);
    $end = new DateTime($to);
    $interval = DateInterval::createFromDateString('1 day');
    $days = new DatePeriod($begin, $interval, $end);

    $baseArray = array();
    foreach ($days as $day) {
        $dateKey = $day->format("Y-m-d");
        $baseArray[$dateKey] = $value;
    }

    return $baseArray;
}

$datesArray = dateArray('2011-01-01', '2011-03-31',true);
Sign up to request clarification or add additional context in comments.

Comments

1

you can try this

function makeDateRange($from,$to,$pattern='m-d-y')
{
    $day = date( $pattern , $from );
    $to = date( $pattern , $to );
    $parseDate = date_parse($from);
    while( $day <= $to ) {
        $day = mktime(0,0,0,$parseDate["month"],$parseDate["day"]+1,$parseDate["year"]);
        $dateArray[] = date($pattern , $day);
        }
    return $dateArray;
}

// here make array $keys = makeDateRange("12-01-11","12-02-11");

//here make above array as key in $a array $a = array_fill_keys($keys, 'none'); print_r($a);

1 Comment

This almost works but only prints out the first date: Array ( [01-12-12] => none ) - If i'm reading it correctly it should load all dates between 12-01-11 and 12-02-11??
1

If I understand you correctly, you could use an associative array for that:

array(
  '00-00-00' => $value,
  '01-01-01' => $value,
  // etc...
);

Or you can create it like this:

$myArray = array();
$myArray['00-00-00'] = $value;
$myArray['01-01-01'] = $value;

You could populate them by running a loop...

Comments

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.