dongyikong6207 2013-12-02 12:28
浏览 42
已采纳

在foreach循环中生成PHP多维数组

I'm looping through an array of days in the current month to generate another array of days that are on or after the current day. I then need to incorporate this into what I believe is a multidimensional array (haven't worked with these types of arrays before). Here's my code that generates the days of the month and compares each one to the current date to get my initial array:

// Set the default timezone
date_default_timezone_set('Australia/Sydney');
$today = date("j");
$firstDayCurrentMonth = date("Y-m-01");

// Get number of days in current month
$days = date("t");
// echo $days;

// Get array of all dates in current month
$aDates = array();
$oStart = new DateTime($firstDayCurrentMonth);
$oEnd = clone $oStart;
$oEnd->add(new DateInterval("P1M"));

while($oStart->getTimestamp() < $oEnd->getTimestamp()) {
    $aDates[] = $oStart->format('j');
    $oStart->add(new DateInterval("P1D"));
}                           

// Setup days array
$days = array();    

// Generate $linked_days array to feed into calendar files 
foreach($aDates as $date) {
    if($date >= $today) {
        $days[] = $date;
    }                    
}

This is all working well so far - I now need to incorporate this array of days into an array in this format:

array("year" => array("month" => array(days)));

For example for the 2nd of Dec, 2013 it would look like this:

$allDays = array("2013" => array("12" => array(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)));

I'm not sure how to insert my array of days into a large multidimensional array?

  • 写回答

1条回答 默认 最新

  • dongqing6755 2013-12-02 13:12
    关注

    Access to multidimension array can use nested [], eg:

    $allDays['2013']['12'] = array(...);
    

    I may have a simpler code for your example:

    <?php
    
    $day = '2nd Dec, 2013';
    $i = strtotime($day);
    
    array("year" => array("month" => array(days)));
    $allDays = array(
        date('Y', $i) => array(
            date('m') => range(date('d', $i), intval(date('t'))),
        ),
    );
    
    var_dump($allDays);
    

    Hope this is helpful to you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮