2

I have an array of objects. Each object includes a date value.

What's the best of filtering the array according to a specific date range, where the range is specified as startDate & endDate?


Update:

Thanks for your replies, I used this code in the end:

 foreach ($myArray as $key => &$value)
 {
      $d = DateTime::createFromFormat(self::DATE_FORMAT, $value["orderDate"]); 
      if ($d->getTimestamp() < $startDateTime->getTimestamp() || $d->getTimestamp() > $endDateTime->getTimestamp())
      {
           unset($myArray[$key]);
      }
 }
1
  • If by chance, these objects originated from a database, you could also alter your SQL query to return the results already sorted by date. You'd use the ORDER BY keywords.. Commented May 19, 2012 at 19:34

3 Answers 3

4

This is the basic idea; you'll have to tweak it for your particular object type and date type.

foreach ($myarray as $item)
    if ($item->dateitem >= $startDate  &&  
        $item->dateitem <= $endDate)
            $newarray[] = $item;
Sign up to request clarification or add additional context in comments.

Comments

3

Assuming your object contains a string representation of a date, we'll convert it to a numeric timestamp using strtotime().

To filter out everything not in a given range (keeps values matching the start/end values):

 $rangeStart = strtotime('-1 year');
 $rangeEnd = strtotime('yesterday');

 array_filter( $array, function($var) use ($rangeStart, $rangeEnd) {
    $utime = strtotime($var->date);
    return $utime <= $rangeEnd && $utime >= $rangeStart;
 });

To sort the array by date:

 function cmp($a, $b) {
    $aTime = strtotime($a->date);
    $bTime = strtotime($b->date);

    if( $aTime === $bTime ) { return 0; }
    else { return $aTime < $bTime? -1 : 1; }
 }

 usort( $array, 'cmp' );

2 Comments

Answers a different question.
Ha! I got half way through answering the question and forgot what I was answering. So you get sort too. Guess I'll go make some tea :)
2
function inRange($thingy) {
  return $thingy->theDate >= $startDate && $thingy->theDate < $endDate;
}

$filtered = array_filter($unfiltered, "inRange");

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.