我使用服务 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 填充新数组,但它不起作用,因为一个小问题:"记录"只能包含一条记录。它可以有"可用":真或"可用":假,这意味着它从当前日期到 2 个月可用或不可用。
也许有人提示我正确的方法?
已解决。按日期排序,然后按日期排序。
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;
}