繁体   English   中英

PHP从数组计算日期范围

[英]PHP calculate date range from array

我使用服务API,该服务API以json格式提供了一个时间表,该时间表描述了日期范围:

.... // Other items
{
  "registration": "SP-TEST",
  "records": [
    {
      "from": "2014-12-06T13:40Z",
      "available": true
    },
    {
      "from": "2014-12-07T14:30Z",
      "available": false
    },
    {
      "from": "2014-12-13T14:30Z",
      "available": true
    },
    {
      "from": "2014-12-13T16:30Z",
      "available": false
    },
    {
      "from": "2014-12-15T14:30Z",
      "available": true
    }
  ]
},
....

但是使用和搜索都不舒服。 我需要将其导入到MySQL DB并在可用的日期范围内执行搜索,因此我需要合并数组,例如:

[{
  "registration": "SP-TEST",
  "from": "2014-12-06T13:40Z",
  "to": "2014-12-07T14:30Z"
},
{
  "registration": "SP-TEST",
  "from": "2014-12-13T14:30Z",
  "to": "2014-12-13T16:30Z"
},
{
  "registration": "SP-TEST",
  "from": "2014-06-06T13:40Z",
  "to": "2014-06-07T14:30Z"
},
{
  "registration": "SP-TEST",
  "from": "2014-12-15T14:30Z",
  "to": "2014-02-07T14:30Z"
}]

我使用usort函数按时间源数组(json_decode($ schedule))进行排序:

usort($schedule->records, function($a, $b) {
    return strtotime($a->from) - strtotime($b->from);
 });

因此,如果此代码正确,我可以使用foreach来填充新数组,但是它不起作用,因为一个小问题:“记录”只能包含一个记录。 它可以具有“ available”:true或“ available”:false,这意味着从当前日期起2个月内它是否可用。

也许有人提示我正确的方法?

解决。 按日期排序,然后foreach。

function schedule($records) {
    date_default_timezone_set('UTC'); // 0 timezone

    $result = array();

    foreach ($records as $k => $v) {
        $record = array_merge($record, array(
            'available' => $v->available,
            'location' => $v->location,
            'from' => $v->from,
            'depart' => '',
            'arrive' => '',
            'to'=>   date("Y-m-d\TH:i\Z", strtotime("+2 month", strtotime($v->from)))
        ));

        if (count($records) > 1) {
            $record['to'] = date("Y-m-d\TH:i\Z", strtotime("+2 month", strtotime($record['from'])));
        }
        if (isset($records[$k+1])) {
            $record['to'] = $records[$k+1]->from;
            $record['depart'] = $v->location;
            $record['arrive'] = $records[$k+1]->location;
        }
        $result[] = $record;
    }

    return $result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM