我要做的是得到日期($date_before_that_expiry),这是$time_to_expiry (6)天前$distinct_expiries (26-10-2017)的格式DD-MM-YYYY。
但是,如果返回日期在数组($trading_holiday_array)中,则应该在前一天移动返回日期($date_before_that_expiry)。这是递归完成的。
例句:如果我得到一个日期20-2017年10月-2017年,最初它应该返回我18-10月-2017年,而不是19,因为19-10月-2017年也是($trading_holiday_array)的一部分。
下面是我写下的代码,但是它进入了一个无限循环:
<?php
$distinct_expiries='26-Oct-2017';
$time_to_expiry=6;
$trading_holiday_array = array('19-Oct-2017', '20-Oct-2017');
$date_before_that_expiry = date('d-M-Y', strtotime("-$time_to_expiry days", strtotime($distinct_expiries)));
while(in_array($date_before_that_expiry, $trading_holiday_array)) {
$new_lookback= -(1+$time_to_expiry)." days";
$date_before_that_expiry = date('d-M-Y', strtotime("$new_lookback", strtotime($distinct_expiries)));
}
echo $date_before_that_expiry;
?>请协助。
发布于 2018-04-21 21:10:17
下面是您的逻辑的一个简单ints实现,您只需要将其传输到DateTime。
<?php
$blocked = [24,32,33,34,35];
$distance = 2;
function getFirstAllowed($i, $blocked, $distance) {
$target = $i-$distance;
while(in_array($target, $blocked)) {
$target--;
}
return $target;
}
// testing:
echo getFirstAllowed(26, $blocked, $distance)."<br>"; // 23
echo getFirstAllowed(27, $blocked, $distance)."<br>"; // 25
echo getFirstAllowed(36, $blocked, $distance)."<br>"; // 31同样的转移到DateTime:
<?php
$blocked = [
new DateTime("2017-10-19"),
new DateTime("2017-10-20")
];
$timeToExpiry = new DateInterval("P6D"); // read as 'Period: 6 Days'. "P1Y3M" would be one year, 3 months
function getFirstAllowed(DateTime $startdate, Array $blocked, DateInterval $timeToExpiry) {
$target = $startdate->sub($timeToExpiry);
$oneDayInterval = new DateInterval("P1D");
while(in_array($target, $blocked)) {
$target->sub($oneDayInterval);
}
return $target;
}
// testing
echo getFirstAllowed(new DateTime("2017-10-25"), $blocked, $timeToExpiry)->format("Y-m-d")."<br>"; // 2017-10-18
echo getFirstAllowed(new DateTime("2017-10-26"), $blocked, $timeToExpiry)->format("Y-m-d")."<br>"; // 2017-10-18
echo getFirstAllowed(new DateTime("2017-10-31"), $blocked, $timeToExpiry)->format("Y-m-d")."<br>"; // 2017-10-25发布于 2018-04-21 21:05:28
我想我在修补一下之后得到了答案:
<?php
$distinct_expiries='26-Oct-2017';
$time_to_expiry=6;
$trading_holiday_array = array('19-Oct-2017', '20-Oct-2017');
$date_before_that_expiry = date('d-M-Y', strtotime("-$time_to_expiry days", strtotime($distinct_expiries)));
while(in_array($date_before_that_expiry, $trading_holiday_array)) {
$time_to_expiry+=1;
$date_before_that_expiry = date('d-M-Y', strtotime("-$time_to_expiry days", strtotime($distinct_expiries)));
}
echo $date_before_that_expiry;
?>我使用的是相同的$time_to_expiry,这使得循环变得无限。-P
如有任何进一步改进之处,将不胜感激。
https://stackoverflow.com/questions/49960058
复制相似问题