PHP 从数组计算日期范围

标签 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 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;
}

关于PHP 从数组计算日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27677664/

相关文章:

php - azure 托管 Web 应用程序上的 html 联系表单

php - 公共(public)页面上的 ID 散列与加密

php - 页边距和右对齐页脚 tcpdf

jquery - Mysql ORDER BY length(col), col 不工作

javascript - 如何隐藏/显示基于数组的元素?

arrays - 在 Fortran 中用另一个模块中的参数名称声明一个数组

php - PDOexecute($input_parameter) 防止 SQL 注入(inject)作为 bindParam/bindValue?

MySQL:更新具有不同列名的多个表?

php - OpenCart与会计软件的集成

javascript - 在一个谷歌脚本下运行多个工作表,语法错误