2015-11-06 79 views
1

这是关于填充给定年份的假期(而不是如何计算它们)的数组,以便随后轻松访问它们。我的方法是使用假期的时间戳作为关键字。如何用假期填充数组?

$year = 2015; 
$holidays = array(
    strtotime($year . '-01-01') => array(
     'holiday' => 'New Year', 
     'comment' => 'Happy New Year!' 
    ), 
    strtotime($year . '-04-05') => array(
     'holiday' => 'Easter', 
     'comment' => 'Happy Easter!' 
    ), 
    strtotime($year . '-12-25') => array(
     'holiday' => 'Christmas', 
     'comment' => 'Merry Christmas!' 
    ) 
    . 
    . 
    . 
); 

这工作得很好,直到有一个每天在同一时间超过一个节日,例如2015年12月6日(圣尼古拉斯节,第一次降临)。在这种情况下,已经定义的键后面的值被覆盖。所以需要另一个数组级别。

$year = 2015; 
$holidays = array(); 
$holidays[strtotime($year . '-01-01')][] => array(
     'holiday' => 'New Year', 
     'comment' => 'Happy New Year!' 
); 
$holidays[strtotime($year . '-04-05')][] => array(
     'holiday' => 'Easter', 
     'comment' => 'Happy Easter!' 
); 
$holidays[strtotime($year . '-12-25')][] => array(
     'holiday' => 'Christmas', 
     'comment' => 'Merry Christmas!' 
); 
$holidays[strtotime($year . '-12-06')][] => array(
     'holiday' => 'St Nicholas\' Day', 
     'comment' => 'Make sure to turn out your boots!' 
); 
$holidays[strtotime($year . '-12-06')][] => array(
     'holiday' => 'First Advent', 
     'comment' => 'Remember to light the first candle on your Advent wreath!' 
); 
. 
. 
. 
); 

可这阵填充中的“一条线”来完成(注意;)作为我的第一个例子吗?你有没有比我的方法更聪明的想法?

+0

作为节日可能会因文化,宗教的变化和国家,也许使用图书馆是一个更好的主意。或者你可以有一个数组来声明每个节假日的细节,并使用'foreach'循环来填充'$ holiday'数组 – Andrew

+0

你建议使用哪个库?你能否详细解释你的第二种方法,因为我真的不明白吗? – Ben

+0

我不能推荐任何图书馆,因为我还没有尝试过自己,但谷歌显示我在第一页https://github.com/michalmanko/php-library-holiday – Andrew

回答

1

我会使用一个普通的0索引数组,然后在数组中为该时间的假期创建另一个字段。

$year = 2015; 
$holidays = array(); 
$holidays[] => array(
     'holiday' => 'New Year', 
     'comment' => 'Happy New Year!', 
     'time' => strtotime($year . '-01-01') 
); 
$holidays[] => array(
     'holiday' => 'Easter', 
     'comment' => 'Happy Easter!', 
     'time' => strtotime($year . '-04-05'), 
); 

... 

然后,如果我需要排序它,我会使用PHP数组排序函数。

至于做这一切在一个声明中,你可以做这样的事情:

$holidays = array(
    strtotime($year . '-04-05') => array(
     array(
      'holiday' => 'Easter', 
      'comment' => 'Happy Easter!', 
     ), 
     array(
      'holiday' => 'Christmas', 
      'comment' => 'Merry Christmas!' 
     ), 
    ), 
); 

只需添加更多的阵列所有德一路下跌......

+0

当然,我也想到了这种方法,但它似乎要难得多,速度慢(随着性能下降)才能获得假期。例如,在打印日历时,如果循环中的当前日期是假日,则需要检查。如果假期的时间戳是关键字,则只需检查当前日期的时间戳是否设置在假日数组中:'$ currentDate = strtotime('today'); echo isset($ holidays [$ currentDate])? $ holidays [$ currentDate]:'';'否则你需要在每一天循环访问数组,不是吗? – Ben

+0

你是指什么排序功能?你会如何做到这一点? – Ben

+0

对不起,这里是数组的排序功能:http://php.net/manual/en/array.sorting.php – Kirkland