简体   繁体   中英

PHP: Filter array by date range

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]);
      }
 }

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;

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' );
function inRange($thingy) {
  return $thingy->theDate >= $startDate && $thingy->theDate < $endDate;
}

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

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