我试图将数组元素放在一个范围内,但未能这样做。在下面解释。
$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');
答案 0 :(得分:6)
您可以使用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);
答案 1 :(得分:0)
很容易:
首先将Date-Strings转换为Timestamps以获取整数。
下一步和可选项,您可以对它们进行排序
最后再次走过日期(现在是整数)并收集你想要的日期范围。
执行此操作时,您可以将整数重新转换为旧日期格式。
多数民众赞成。
不超过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);