您可以使用array_filter
Docs和满足您需求的回调来做到这一点:
$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);