从数组重写日期到范围

时间:2012-10-02 03:52:23

标签: php arrays max min

我需要重写每个酒店房间可用数组的日期范围。这是我的数组值:

1=2012-10-07
1=2012-10-08
1=2012-10-09
1=2012-10-10
2=2012-10-07
2=2012-10-08
2=2012-10-09
2=2012-10-10
3=2012-10-05
3=2012-10-06
3=2012-10-08
3=2012-10-09
3=2012-10-10

我需要写下来:

1 available from 7-10 October 2012 //I know this line need to use date("F Y",strtotime());
2 available from 7-10 October 2012 
3 available from 5-10 October 2012

请建议如何在PHP中将这些天数写入日期范围。的问候,

3 个答案:

答案 0 :(得分:3)

这样的事情应该有效:

$dates = array('2000-10-02', '2000-10-01', '2000-10-03');
sort($dates);

// prints "1-3 October 2000"
echo date('j', strtotime(current($dates))) . '-'
   . date('j', strtotime(end($dates))) . ' '
   . date('F Y', strtotime(current($dates)));

改进领域:

  • 当日间范围不连续时会发生什么?
  • 当一个范围跨越两个不同的年份或月份时会发生什么?

答案 1 :(得分:2)

你去http://codepad.viper-7.com/EKo9ky

$dates = array(
    array(1, "2012-10-07"),
    array(1, "2012-10-08"),
    array(1, "2012-10-09"),
    array(1, "2012-10-10"),
    array(2, "2012-10-07"),
    array(2, "2012-10-08"),
    array(2, "2012-10-09"),
    array(2, "2012-10-10"),
    array(3, "2012-10-05"),
    array(3, "2012-10-06"),
    array(3, "2012-10-08"),
    array(3, "2012-10-09"),
    array(3, "2012-10-10")
);
$info = array();
foreach($dates as $roominfo) {
    $time = strtotime($roominfo[1]);
    $room = $roominfo[0];
    if(!array_key_exists($roominfo[0], $info))
        $info[$room] = array($time, $time);
    if($time<$info[$room][0])
        $info[$room][0] = $time;
    if($time>$info[$room][1])
        $info[$room][1] = $time;
}

foreach($info as $roomId => $roomRange) {
    echo $roomId.' available from '.
        date('d', $roomRange[0]).' - '.
        date('d F Y', $roomRange[1]).' <br/>';
}

输出:

1 available from 07 - 10 October 2012
2 available from 07 - 10 October 2012
3 available from 05 - 10 October 2012

这并不能完全符合您的要求,但我认为这应该足以达到您的目标。小心,房间一定不能在一定范围内的一天,请记住这一点。

答案 2 :(得分:1)

以下是有关如何完成任务的一些流程。

首先根据您的1,2,3

切片

那么您可以像这样处理日期:

不使用sort,current,end。我们可以使用最小和最大数组;

<?php
$dates = array('2012-10-07','2012-10-10','2012-10-01');
$stimes = array_map('strtotime',$dates);

var_dump($dates);
var_dump($stimes);

echo date('F j, Y', min($stimes));
echo "<br />\n";
echo date('F j, Y', max($stimes));