开发者

php: possible to convert array of numbers to 'from' and 'to' pairs where consecutive?

  • I have an array of timestamps referring to the days when a holiday home is booked.
  • each timestamp is a round day.
  • I want to turn this into an array of 'begins' and 'ends' pairs for consecutive dates

Are there any php functions I should be aware of for writing this function?

Or does anyone have any pointers for this kind of thing?

thanks!

edit:

example array:

Array
(
    [0] => 1273536000
    [1] => 1273622400
    [2] => 1273708800
    [3] => 1273795200
    [4] => 1273881600
    [5] => 1273968000
    [6] => 1274054400
    [7] => 127414080开发者_运维技巧0
    [8] => 1274227200
)

where a day = 86400 (seconds)


If an end date always follows a begin date, you can use PHP array_chunk()

<?php

$dates = array('2010-05-01', '2010-05-08', '2010-05-14', '2010-05-19');

$bookings = array_chunk($dates, 2);

# bookings
# Array (
#   [0] => Array (
#     [0] => 2010-05-01,   #begin
#     [1] => 2010-05-08    #end
#   ),
#   [1] => Array (
#     [0] => 2010-05-14,   #begin
#     [1] => 2010-05-19    #end
#   )
# )

?>


It's not super pretty, but I think this is what you want:

<?

$d[0] = 1273536000;
$d[1] = 1273622400;
$d[2] = 1273708800;
$d[3] = 1273795200;
$d[4] = 1273881600;
$d[5] = 1273968000;
$d[6] = 1274054400;
$d[7] = 1274140800;
$d[8] = 1274227200;
$d[9] = $d[8] + (60*60*24*4); // 4 days later
$d[10] = $d[9] + (60*60*24); // 1 day after that

$start = 0;
$dates = array();
foreach( $d as $key => $date )
{

// set the start date
if( $start == 0 )
   $start = $date;

else
{
   // set the end date
   if( $date - $d[$key-1] > (60*60*24) || $key == count( $d ) -1 )
   {
      if( $key == count( $d ) -1 )
        $end = $date;
      else      
        $end = $d[$key-1];

      $span['start'] = $start;
      $span['end'] = $end;

      array_push( $dates, $span );

      $start = $date;
    } // if
 } // else
} // foreach

?>

# Results
# Array
# (
#     [0] => Array
#         (
#             [start] => 1273536000 // May 10, 2010
#             [end] => 1274227200 // May 18, 2010
#         )
# 
#     [1] => Array
#         (
#             [start] => 1274572800  // May 22, 2010
#             [end] => 1274659200 //May 23, 2010
#         )
# 
# )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜