从今天起向后排序数月数组

时间:2012-09-30 10:43:46

标签: php

我有以下数组,需要从当前月份向后排序 - 我得到的只是NULL

以下是我正在尝试的内容:

$months = array(
'January' => 0,
'February' => 0,
'March' => 0,
'April' => 0,
'May' => 0,
'June' => 0,
'July ' => 0,
'August' => 0,
'September' => 0,
'October' => 0,
'November' => 0,
'December' => 0,
);

$current = date('F');
$start = array_search($current, $months);

$toshow = array();
$total = 0;
for($i = $start; $total < 12; $i--)
{
if($i == 0)
{
    $i = 12;
}

$toshow[] = $months[$i];
$total++;
}

var_dump($toshow);

我得到的结果是:

array(12) { [0]=> NULL [1]=> NULL [2]=> NULL [3]=> NULL [4]=> NULL [5]=> NULL [6]=> NULL [7]=> NULL [8]=> NULL [9]=> NULL [10]=> NULL [11]=> NULL } 

5 个答案:

答案 0 :(得分:0)

使用krsort():此函数按相反顺序对数组进行排序,保持与值的相关性,此函数对于关联数组非常有用。

krsort($months );

print_r($months );

LIve EXample

答案 1 :(得分:0)

krsort($ toshow = cal_info(CAL_GREGORIAN));`会给你一个反向排序的月数组。

答案 2 :(得分:0)

尝试

$current = date('F');
$arr = array_combine(range(1,12), array_keys($months));
$start = array_search($current, $arr);
//$start = date('n');
for ($i=$start;$i<=12;$i++) {
  $arr_sorted[$arr[$i]] = $months[$arr[$i]];
}
for ($i=1;$i<$start;$i++) {
  $arr_sorted[$arr[$i]] = $months[$arr[$i]];
}
print_r($arr_sorted);

答案 3 :(得分:0)

我认为这可以满足您的需求:

$months = array(
'January' => 0,
'February' => 0,
'March' => 0,
'April' => 0,
'May' => 0,
'June' => 0,
'July ' => 0,
'August' => 0,
'September' => 0,
'October' => 0,
'November' => 0,
'December' => 0,
);

$current = date('F');
$keys = array_keys($months);
$start = array_search($current, $keys);
$toshow = array();


for($i=$start+12; $i>$start; $i--) {
  $key = $i % 12;
  $toshow[$keys[$key]] = $months[$keys[$key]];
}

var_dump( $toshow );

输出:

array(12) { 
  ["September"]=> int(0) 
  ["August"]=> int(0) 
  ["July "]=> int(0) 
  ["June"]=> int(0) 
  ["May"]=> int(0) 
  ["April"]=> int(0) 
  ["March"]=> int(0) 
  ["February"]=> int(0) 
  ["January"]=> int(0) 
  ["December"]=> int(0) 
  ["November"]=> int(0) 
  ["October"]=> int(0) 
}

答案 4 :(得分:0)

为什么需要使用静态值取数组然后向后排序。您可以将数组本身向下移动,如下所示

无需使用此数组

$months = array(
'January' => 0,
'February' => 0,
'March' => 0,
'April' => 0,
'May' => 0,
'June' => 0,
'July ' => 0,
'August' => 0,
'September' => 0,
'October' => 0,
'November' => 0,
'December' => 0,
);

您可以直接向后生成$ months数组。

$months = array();
$currentMonth = (int)date('m');

for($x = $currentMonth; $x >=$currentMonth-12; $x--) {
    $months[date('F', mktime(0, 0, 0, $x, 1))] = 0;
}

echo "<pre>";
print_r ($months);

现在您的阵列本身看起来像您预期的那样

Array
(
    [September] => 0
    [August] => 0
    [July] => 0
    [June] => 0
    [May] => 0
    [April] => 0
    [March] => 0
    [February] => 0
    [January] => 0
    [December] => 0
    [November] => 0
    [October] => 0
)

请参阅输出:http://codepad.org/WuBBYeUh