我使用服务 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/