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

Deb*_*his -1 php arrays

我试图让数组元素在一个范围内,但没有这样做.在下面解释.

$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';
Run Code Online (Sandbox Code Playgroud)

我想从$ 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');
Run Code Online (Sandbox Code Playgroud)

hak*_*kre 6

你可以使用array_filterDocs和满足你需求的回调来做到这一点:

$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'));
Run Code Online (Sandbox Code Playgroud)

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


对于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);
Run Code Online (Sandbox Code Playgroud)