gpt4 book ai didi

PHP 在区间内查找所有可能的日期组合

转载 作者:行者123 更新时间:2023-11-29 05:20:52 25 4
gpt4 key购买 nike

我有两个日期,即事件开始日期和结束日期,在我的 php 脚本中我想找出这两个日期之间所有可能的日期组合

我的意思是我想找出参与者参加事件的所有可能日期,

假设开始日期为2014/10/23,结束日期为2014/10/23,

所有可能的组合都是

  1. 20/10/2014 -23/10/2014
  2. 20/10/2014 -22/10/2014
  3. 20/10/2014 -21/10/2014
  4. 21/10/2014 -23/10/2014
  5. 21/10/2014 -22/10/2014
  6. 22/10/2014 -23/10/2014
  7. 20/10/2014 -21/10/2014- 22/10/2014
  8. 20/10/2014 -21/10/2014- 22/10/2014 -23/10/2014
  9. 21/10/2014 -22/10/2014 -23/10/2014

我想找出所有可能的组合的原因是,我有不同的折扣选项基于事件参与者的日 session 。

最佳答案

这个问题可以分为两部分:

  1. 对于任意两个日期,创建一个包含日期间隔内所有日期的数组。
  2. 创建所有可能天数的所有可能组合(从 1 到 n,其中 n == 间隔内的天数)。

对于第一部分,我将使用 DatePeriod PHP 类,第二个 Math_Combinatorics梨包。这是完整的代码:

require_once 'Math/Combinatorics.php';

date_default_timezone_set('UTC');

$format = "d/m/Y";
$start = DateTime::createFromFormat($format, "20/10/2014");
$end = DateTime::createFromFormat($format, "23/10/2014");

$period = new DatePeriod($start, new DateInterval('P1D'), $end);

$dates = array();
foreach ($period as $date) {
$dates[] = $date->format($format);
}

$dates[] = $end->format($format);

$combinations = array();
$combinatorics = new Math_Combinatorics();

foreach (range(1, count($dates)) as $number_of_combinations) {
foreach ($combinatorics->combinations($dates, $number_of_combinations) as $combination) {
$combinations[] = $combination;
}
}

print_r($combinations);

结果:

Array
(
[0] => Array
(
[0] => 20/10/2014
)

[1] => Array
(
[0] => 21/10/2014
)

[2] => Array
(
[0] => 22/10/2014
)

[3] => Array
(
[0] => 23/10/2014
)

[4] => Array
(
[0] => 20/10/2014
[1] => 21/10/2014
)

[5] => Array
(
[0] => 20/10/2014
[2] => 22/10/2014
)

[6] => Array
(
[0] => 20/10/2014
[3] => 23/10/2014
)

[7] => Array
(
[1] => 21/10/2014
[2] => 22/10/2014
)

[8] => Array
(
[1] => 21/10/2014
[3] => 23/10/2014
)

[9] => Array
(
[2] => 22/10/2014
[3] => 23/10/2014
)

[10] => Array
(
[0] => 20/10/2014
[1] => 21/10/2014
[2] => 22/10/2014
)

[11] => Array
(
[0] => 20/10/2014
[1] => 21/10/2014
[3] => 23/10/2014
)

[12] => Array
(
[0] => 20/10/2014
[2] => 22/10/2014
[3] => 23/10/2014
)

[13] => Array
(
[1] => 21/10/2014
[2] => 22/10/2014
[3] => 23/10/2014
)

[14] => Array
(
[0] => 20/10/2014
[1] => 21/10/2014
[2] => 22/10/2014
[3] => 23/10/2014
)

)

关于PHP 在区间内查找所有可能的日期组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25970377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com