1

我有以下数组,需要从当前月份向后排序 - 我得到的是 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 } 
4

5 回答 5

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) 
}
于 2012-09-30T10:57:46.783 回答
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

于 2012-09-30T11:03:20.130 回答
0

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

krsort($months );

print_r($months );

活例

于 2012-09-30T10:49:07.783 回答
0

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

于 2012-09-30T10:49:59.967 回答
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);
于 2012-09-30T10:55:54.273 回答