首页 > 解决方案 > 从返回“内部”数组的多个循环创建 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 
            ) 
    )

标签: php

解决方案


您已经很接近了,只需在 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


推荐阅读