简体   繁体   English

PHP:按日期范围过滤数组

[英]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? 根据特定的日期范围过滤数组最好的是什么,其中范围指定为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 (). 假设您的对象包含日期的字符串表示,我们将使用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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM