1、使用递归方法实现
public function test($start, $end, $price, $deep) {
global $total;
if ($deep > 100) {
log_message('info', '出现了超过100天的数据.' . __FUNCTION__ . '>>>' . $price);
return $total;
}
$at = strtotime(date('Y-m-d', $start) . ' ' . $price[0]['end']);
$et = strtotime(date('Y-m-d', $start) . ' ' . $price[1]['end']);
if ($end >= $et) {
$new_start = $et;
$new_end = $end;
$deep = $deep + 1;
$end = $et;
}
if ($start < $at && $end <= $at) {
$hour = ceil(($end - $start) / 3600);
$total += $price[0]['price'] * $hour;
}
if ($start < $at && $end > $at && $end <= $et) {
$one = ceil(($at - $start) / 3600) * $price[0]['price'];
$two = ceil(($end - $at) / 3600) * $price[1]['price'];
$total += $one + $two;
}
if ($start >= $at && $end <= $et) {
$hour = ceil(($end - $start) / 3600);
$total += $price[1]['price'] * $hour;
}
if (isset($new_end) && isset($new_start)) {
unset($start);
unset($end);
unset($at);
unset($et);
$this->test($new_start, $new_end, $price, $deep);
}
return $total;
}
2、使用时间偏移计算
/**
* 以格林泥治时间为中心,计算差值
* @param $start 开始时间戳
* @param $end 结束时间戳
* @param $price [{"start":"00:00:00","end":"12:00:00","price":1000},{"start":"12:00:00","end":"24:00:00","price":1500}]
* @return float|int
*/
public function test2($start, $end, $price) {
$date1 = $start + 8 * 3600;
$date2 = $end + 8 * 3600;
$dt1 = 86400 - ($date1 % 86400);
$dt2 = $date2 % 86400;
$gap = $date2 - $date1 - $dt1 - $dt2;
$parsed = date_parse($price[0]['end']);
$one = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
$two = 86400 - $one;
$one_p = ($one / 3600) * $price[0]['price'];
$two_p = ($two / 3600) * $price[1]['price'];
$total = ($gap / 86400) * ($one_p + $two_p);
if ($dt1 > $two) {
$total += $two_p;
$total += ceil(($dt1 - $two) / 3600) * $price[0]['price'];
} else {
$total += ceil($dt1 / 3600) * $price[1]['price'];
}
if ($dt2 > $one) {
$total += $one_p;
$total += ceil(($dt2 - $one) / 3600) * $price[1]['price'];
} else {
$total += ceil($dt2 / 3600) * $price[0]['price'];
}
return $total;
}