在当前月份对数组进行排序

时间:2013-08-20 16:59:18

标签: php arrays sorting

我要做的是按当前月份对当前数组进行排序,依此类推。我得到了当前的月份,但无法找到一种方法来对其进行排序以使其正确排序。

当前输出是(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;
            }
        }
    }

?>

1 个答案:

答案 0 :(得分: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对象。