PHP从数组计算日期范围

时间:2014-12-28 15:13:10

标签: php mysql arrays

我使用服务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数据库并在可用的日期范围内执行搜索,所以我需要组合数组,如:

[{
  "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来填充新数组,但它不起作用,因为一个小问题:“records”只能包含一条记录。它可以具有“可用”:true或“available”:false,这意味着它可以在当前日期2个月之前可用或不可用。

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

1 个答案:

答案 0 :(得分:0)

解决。按日期排序,然后是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;
}