douangoo48863 2019-02-11 14:34
浏览 221
已采纳

从多个时间段创建连续时间线

Hey stackoverflow community,

I'm currently trying to archive an continuous timeline from an array of time periods. My input array looks like this:

$array = array(
0 => array(
    'from' => '2019-01-01 00:00:00',
    'to' => '2019-03-31 00:00:00'
),
1 => array(
    'from' => '2019-02-04 00:00:00',
    'to' => '2019-03-15 00:00:00'
));

And the result I'm looking for, is this:

$array = array(
0 => array(
    'from' => '2019-01-01 00:00:00',
    'to' => '2019-02-03 23:59:59'
),
1 => array(
    'from' => '2019-02-04 00:00:00',
    'to' => '2019-03-14 23:59:59'
),
2 => array(
    'from' => '2019-03-15 00:00:00',
    'to' => '2019-03-31 00:00:00'
));

As hard as I'm trying, I'm unable to find a proper solution. Has anyone an idea how to solve this in PHP?

  • 写回答

2条回答 默认 最新

  • doureng5668 2019-02-11 15:05
    关注

    Simply convert all times into Unix timestamps, put them into a simple array, sort and then convert them back to datetimes by constructing the desired array:

    <?php
    $array = array(
        0 => array(
            'from' => '2019-01-01 00:00:00',
            'to' => '2019-03-31 00:00:00'
        ),
        1 => array(
            'from' => '2019-02-04 00:00:00',
            'to' => '2019-03-15 00:00:00'
        ));
    
    $unixTS = array();
    foreach ($array as $arr => $times) {
        foreach ($times as $str => $time) {
            $unixTS[] = strtotime($time);
        }
    }
    
    sort($unixTS);
    
    $newArray = array();
    for ($i = 0; $i < count($unixTS); $i++) {
        if ($i < count($unixTS) - 1) {
            if ($i + 2 >= count($unixTS))
                $newArray[] = array('from' => date("Y-m-d H:i:s", $unixTS[$i]), 'to' => date("Y-m-d H:i:s", $unixTS[$i + 1]));
            else
                $newArray[] = array('from' => date("Y-m-d H:i:s", $unixTS[$i]), 'to' => date("Y-m-d H:i:s", $unixTS[$i + 1] - 1));
        }
    }
    
    print_r($newArray);
    

    Output:

    Array
    (
    [0] => Array
        (
            [from] => 2019-01-01 00:00:00
            [to] => 2019-02-03 23:59:59
        )
    
    [1] => Array
        (
            [from] => 2019-02-04 00:00:00
            [to] => 2019-03-14 23:59:59
        )
    
    [2] => Array
        (
            [from] => 2019-03-15 00:00:00
            [to] => 2019-03-31 00:00:00
        )
    )
    

    Probably playing with $i index is not the most elegant way, but you can get the concept and improve your code if needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!