要求是生成指定时间段内特定日期的日期列表,即 2019 年 5 月至 2019 年 9 月的每个星期四。
期望格式为:
Array
(
[0] => 2019-05-02
[1] => 2019-05-09
[2] => 2019-05-16
[3] => 2019-05-23
[4] => 2019-05-30
[5] => 2019-06-06
[6] => 2019-06-13
[7] => 2019-06-20
[8] => 2019-06-27
[9] => 2019-07-04
[10] => 2019-07-11
[11] => 2019-07-18
[12] => 2019-07-25
[13] => 2019-08-01
[14] => 2019-08-08
[15] => 2019-08-15
[16] => 2019-08-22
[17] => 2019-08-29
[18] => 2019-09-05
[19] => 2019-09-12
[20] => 2019-09-19
[21] => 2019-09-26
)
当前代码是:
function getCompDates($y, $m) {
$allDates = [];
$current = strtotime("first thursday of $y-$m");
$end = strtotime("last day of $y-$m");
while ($current <= $end) {
$allDates[] = date('Y-m-d', $current);
$current = strtotime('next thursday', $current);
}
return $allDates;
}
$thursdays = [];
$thursdays_tmp = [];
for ($i = 5; $i <= 9; $i++) {
$thursdays_tmp[] = getCompDates(2019, sprintf('%02d', $i));
print_r($thursdays_tmp);
}
我真的只想将 $thursday
数组作为我的结果。我添加了 $thursday_tmp
变量用于“内部”循环处理,然后最终合并回 $thursday
但是,在循环的最后一次运行时,$thursday_tmp
数组如下所示:
Array
(
[0] => Array
(
[0] => 2019-05-02
[1] => 2019-05-09
[2] => 2019-05-16
[3] => 2019-05-23
[4] => 2019-05-30
)
[1] => Array
(
[0] => 2019-06-06
[1] => 2019-06-13
[2] => 2019-06-20
[3] => 2019-06-27
)
[2] => Array
(
[0] => 2019-07-04
[1] => 2019-07-11
[2] => 2019-07-18
[3] => 2019-07-25
)
[3] => Array
(
[0] => 2019-08-01
[1] => 2019-08-08
[2] => 2019-08-15
[3] => 2019-08-22
[4] => 2019-08-29
)
[4] => Array
(
[0] => 2019-09-05
[1] => 2019-09-12
[2] => 2019-09-19
[3] => 2019-09-26
)
)
最佳答案
你已经很接近了,只需在 for 循环中更改此代码即可将所有数组合并为一个:
for ($i = 5; $i <= 9; $i++) {
$thursdays_tmp = array_merge($thursdays_tmp, getCompDates(2019, sprintf('%02d', $i)));
}
print_r($thursdays_tmp);
完整的代码可以在这里查看和运行:http://sandbox.onlinephpfunctions.com/code/11439d56c14229acf23ad57a07f71aa88f944040
关于php - 从返回 "outer"数组的多个循环创建 1 "inner"数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55949277/