如何获取范围内的数组元素


How to get the array elements within a range

我试图在一个范围内获取数组元素,但失败了。下面解释一下。

$date_array = array('2012-08-02','2012-08-09','2012-08-16','2012-08-23');
$start_date = '2012-08-01';
$end_date   = '2012-08-10';

我想从 $start_date 和 $end_date 中的 $date_array 中获取数组元素。即输出将是:2012-08-02和2012-08-09。

编辑:

数组也可以如下所示。

$date_array = array('2012-08-02','2012-08-10','2012-08-16','2012-08-23');
您可以使用

array_filter文档和满足您需求的回调来执行此操作:

$filter = function($start, $end) {
    return function($string) use ($start, $end) {
        return $string >= $start && $string <= $end;
    };
};
$result = array_filter($array, $filter('2012-08-01', '2012-08-10'));

注意参数的顺序,以及您拥有这些确切的格式,因为只有那些可以通过简单的字符串比较来完成。


对于 PHP 5.2 的兼容性,以及为了解决迭代器而不仅仅是数组的问题,这里有一个更通用的方法:

class Range
{
    private $from;
    private $to;
    public function __construct($from, $to) {
        $this->from = $from;
        $this->to = $to;
        if ($from > $to) {
            $this->reverse();
        }
    }
    private function reverse() {
        list($this->from, $this->to) = array($this->to, $this->from);
    }
    public function in($value) {
        return $this->from <= $value && $value <= $this->to;
    }
}
class RangeFilter extends FilterIterator
{
    private $range;
    public function __construct(Iterator $iterator, Range $range) {
        $this->range = $range;
        parent::__construct($iterator);
    }
    public function accept()
    {
        $value = $this->getInnerIterator()->current();
        return $this->range->in($value);
    }
}
$range = new Range($start, $end);
$it = new ArrayIterator($array);
$filtered = new RangeFilter($it, $range);
$result = iterator_to_array($filtered);

这很简单:

首先将日期字符串转换为时间戳以获取整数。
接下来和可选的,您可以对它们进行排序。
最后,再次浏览日期(现在是整数)并收集所需的日期范围。
执行此操作时,您可以将整数重新转换为旧的日期格式。

仅此而已。
不超过 10 行代码。

好的,有些人想要一个例子。在这里:

// create a bunch of unsortable random dates-trash
$dates = array();
for($i = 0; $i < 100; $i ++)
    $dates[] = date('Y-m-d', rand(1000, time()));
// first transform it to timestamp integers
// if strtotime don't makes it, you have to transform your datesformat
// as one more pre-step
foreach($dates as $k => $v)
    $dates[$k] = strtotime($v);
// now and optional sort that (now finest) stuff
sort($dates);
// at last get the range of dates back
$datesInRange = array();
$dateStart = strtotime('1998-06-27');
$dateEnd = strtotime('2010-4-20');
foreach($dates as $date)
    if($date >= $dateStart AND $date <= $dateEnd)
        $datesInRange[] = date('Y-m-d', $date);
// have a look at the result
echo implode(',<br />', $datesInRange);