PHP:按日期范围过滤数组


PHP: Filter array by date range

我有一个对象数组。每个对象都包含一个日期值。

根据特定日期范围过滤数组的最佳方法是什么,其中范围被指定为 startDate 和 endDate?


更新:

感谢您的回复,我最后使用了这段代码:

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

这是基本思想; 您必须针对特定的对象类型和日期类型对其进行调整。

foreach ($myarray as $item)
    if ($item->dateitem >= $startDate  &&  
        $item->dateitem <= $endDate)
            $newarray[] = $item;

假设您的对象包含日期的字符串表示形式,我们将使用 strtotime(( 将其转换为数字时间戳。

要过滤掉不在给定范围内的所有内容(保持值与开始/结束值匹配(:

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

按日期对数组进行排序:

 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");