php – 有没有更有效的方法来创建年/月的列表?
作者:互联网
在页面上,我想动态列出每年的年份和所有月份,以便查看每个月的存档.我想先显示当前年份,但今年可能还没有结束,所以我只想显示已经过去的月份和当月.然后我想要从今年开始的所有年份和所有月份(即2008年).
我创建的PHP代码完成了以下工作.有没有更有效的方法来实现这一目标?我正在运行PHP 5.2.
$current_year = date('Y');
$months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
// Loop through all the months and create an array up to and including the current month
foreach ($months as $month)
{
if ($month <= date('m'))
{
switch ($month)
{
case 1:
$years[$current_year][] = 'January';
break;
case 2:
$years[$current_year][] = 'February';
break;
case 3:
$years[$current_year][] = 'March';
break;
case 4:
$years[$current_year][] = 'April';
break;
case 5:
$years[$current_year][] = 'May';
break;
case 6:
$years[$current_year][] = 'June';
break;
case 7:
$years[$current_year][] = 'July';
break;
case 8:
$years[$current_year][] = 'August';
break;
case 9:
$years[$current_year][] = 'September';
break;
case 10:
$years[$current_year][] = 'October';
break;
case 11:
$years[$current_year][] = 'November';
break;
case 12:
$years[$current_year][] = 'December';
break;
}
}
}
// Previous years
$years_to_create = $current_year - 2008;
if (!empty($years_to_create))
{
for ($i = 1; $i <= $years_to_create; $i++)
{
$years[$current_year - $i] = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
}
}
解决方法:
$current_year = date('Y');
$months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
$month_names = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
// Loop through all the months and create an array up to and including the current month
for ($month=1;$month<=date('m');$month++)
{
$years[$current_year][] = $month_names[$month-1];
}
// Previous years
$years_to_create = $current_year - 2008;
if (!empty($years_to_create))
{
for ($i = 1; $i <= $years_to_create; $i++)
{
$years[$current_year - $i] = $month_names;
}
}
这似乎有点简单……是否更快……?
标签:php,performance,datetime,language-agnostic 来源: https://codeday.me/bug/20190827/1744151.html