2013-08-20 88 views
0

我想要做的是按當前月份排序當前數組,以此類推。我得到了當前的月份,但無法找出一種方法來排序它,使其正確排序。排序數組基於本月

當前輸出是(1月=> 12月),但想**(8月=> 7月)。 **本月是什麼。

<?php 

    $mons = array(1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May", 6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October", 11 => "November", 12 => "December"); 

    $getdate = getdate(); 
    $months = $getdate['mon']; 

    $month_name = $mons[$months]; 

    echo $month_name; 

    $month_arr = Array( 
     'January' => Array('num_dates'=>0, 'dates'=>Array()) , 
     'February' => Array('num_dates'=>0, 'dates'=>Array()), 
     'March' => Array('num_dates'=>0, 'dates'=>Array()), 
     'April' => Array('num_dates'=>0, 'dates'=>Array()), 
     'May' => Array('num_dates'=>0, 'dates'=>Array()), 
     'June' => Array('num_dates'=>0, 'dates'=>Array()), 
     'July' => Array('num_dates'=>0, 'dates'=>Array()), 
     'August' => Array('num_dates'=>0, 'dates'=>Array()), 
     'September' => Array('num_dates'=>0, 'dates'=>Array()), 
     'October' => Array('num_dates'=>0, 'dates'=>Array()), 
     'November' => Array('num_dates'=>0, 'dates'=>Array()), 
     'December' => Array('num_dates'=>0, 'dates'=>Array()) 
    ); 

    $date_arr = Array(); 

    $date_start = 'Aug 02, 2013'; 
    $date_arr[] = date('M d, Y', strtotime($date_start)); 


    for ($i=1; $i<=24; $i++){ 
     $date_temp = date('M d, Y', strtotime($date_arr[$i-1] . "+ 14 day")); 
     $month = date('F', strtotime($date_temp)); 

     $month_arr[$month]['dates'][] = $date_temp; 
     $month_arr[$month]['num_dates'] += 1; 
     $date_arr[] = $date_temp; 
    } 

    foreach ($month_arr as $k => $v){ 
     if (!empty($v)){ 
      if ($v['num_dates'] != 0){ 
       echo "<BR><BR>Month: " . $k; 
      } 
     } 
    } 

?> 
+3

我強烈建議使用PHP內置的DateTime對象。這裏:http://php.net/manual/en/book.datetime.php – Saturnix

+0

如果你想排序一個數組,請看['usort'](http://php.net/usort)。 –

+1

聽起來像您正在過濾...不排序... – Orangepill

回答

0

這是從當前月份開始循環訪問月數組的快速方法。

$m = 0; 
for ($i = 0; $i < 12; $i++) { 
    $month = date('F', strtotime("+{$m} months")); 
    echo $month . "<br>"; 
    //$month_arr[$month]; //to access your array 
    $m++; 

} 

如上所述,您也可以使用DateTime對象。