2011-10-06 53 views
0

我有形式的兩個日期:PHP生成與年份和月份顯示的數字陣列

開始日期: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行。

+0

這是不是真的清楚自己想要做什麼。你能詳細解釋一下嗎? – ronakg

+0

我想用數組生成一個表格。用戶只能輸入from和end date。我希望它按月分組。 – Shiro

回答

0
$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

+0

你的傢伙真棒!反應非常快!尊重 – Shiro

2
$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)); 
0
<?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