【问题标题】:PHP Generate Array with number of month and year displayPHP生成带有月份和年份显示的数组
【发布时间】:2011-10-06 07:14:59
【问题描述】:

我有两个日期的表格:

开始日期:2010-12-24
结束日期:2011-10-06(今天)

现在我需要从上面的开始日期和结束日期开始按月为这个组生成一个数组:

$arr_month['oct_11'] = array(
   'month'   => 'October 2011'
 );
 . 
 . 
 .
$arr_month['feb_11'] = array(
   'month'   => 'Feb 2011'
 );

$arr_month['jan_11'] = array(
   'month'   => 'January 2011'
 );

$arr_month['dec_10'] = array(
   'month'   => 'December 2010'
 );

如您所见,如果我使用此数组生成表格,表格中应该有 11 行。

【问题讨论】:

  • 不清楚你想做什么。你能详细说明一下吗?
  • 我想用数组生成一个表。用户只输入开始日期和结束日期。我希望它按月分组。

标签: php arrays datetime datediff


【解决方案1】:
$start = "2010-12-24";
$end = "2011-10-06";

function enumerate($start,$end) {
        $start = strtotime($start);
        $end = strtotime($end . "+1 month");
        $range = range($start,$end,60*60*24*31);
        $formatted = array();
        foreach($range as $date) {
        $key = strtolower(str_replace(" ","_",date("M Y",$date)));
        $formatted[$key] = array(

                        "month" => date('M Y',$date),
                        "amount" => "365"
                );
        }       
        return $formatted;
}

var_dump(enumerate($start,$end));

【讨论】:

    【解决方案2】:
    $start_date = '2010-12-24';
    $end_date = '2011-10-06';
    
    function getMonthArray($start_date, $end_date){
        $start_timestamp = strtotime(str_replace('-', '/', $start_date));
        $end_timestamp = strtotime(str_replace('-', '/', $end_date));
    
        $start_month_timestamp = strtotime(date('F Y', $start_timestamp));
        $current_month_timestamp = strtotime(date('F Y', $end_timestamp));
    
        $arr_month = array();
    
        while( $current_month_timestamp >= $start_month_timestamp ) {
            $arr_month[strtolower(date('M_y', $end_timestamp))] = date('F Y', $end_timestamp);
            $end_timestamp = strtotime('-1 month', $end_timestamp);
    
            $current_month_timestamp = strtotime(date('F Y', $end_timestamp));
        }
    
        return $arr_month;
    }
    
    $arr_month = getMonthArray($start_date, $end_date);
    

    Demo

    【讨论】:

    • 你们太棒了!反应真快!尊重
    【解决方案3】:
    <?php
    
    $start = strtotime(substr_replace('2010-12-24', '01', -2));
    $end = strtotime('2011-10-06');
    
    $time = $start;
    $arr_month = array();
    while ($time <= $end) {
        $arr_month[strtolower(date('M_y', $time))]['month'] = date('F Y', $time);
        $time += date('t', $time) * 24 * 60 * 60;
    }
    
    var_dump($arr_month);
    

    http://ideone.com/ozLOx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2018-06-28
      相关资源
      最近更新 更多