php - 从返回“内部”数组的多个循环创建 1 个“外部”数组
问题描述
要求是在定义的时间段内(即 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
推荐阅读
- asp.net - ASP.NET Core 2.1 管理页面出现奇怪的子菜单
- c++11 - 使用 std::bind 和 std::function 时回调失败
- amazon-dynamodb - DynamoDB 邻接列表是否应该使用离散的分区键来为每种类型的关系建模?
- react-native - React Navigation version 3 falied to load page
- python - 有没有更快的方法从 Colab 同步驱动器
- c - 编译从 matlab 生成的 C 文件时出现此错误
- pdf - 在 LaTeX 中裁剪 PDF 文件作为输出
- java - 练习同步和线程
- c# - 如何根据下拉列表中的选定项目使表单响应(显示/隐藏表单的部分)?
- ios - 以编程方式从图像中检测肤色