我需要以表格形式向用户显示本地化的日期名称列表(例如“星期一”,“星期二”,...)。我知道该如何获取任何日期的日期名称。但是是否有一种特殊且可靠的方法来获取数组中的全天名称。
编辑:我可以将天的名称添加到我的翻译文件中,但是很难维护。
最佳答案
将strftime()
与setlocale()
结合使用是一种选择。
但是,您应该意识到,在线程安装php时,setlocale()
的行为可能会异常,因为区域设置信息是按进程而不是按线程维护的。因此重要的是,每次调用setlocale()
之前都要每次调用strftime()
以确保它使用正确的语言环境。
同样,对于Windows系统,您需要为$locale
的setlocale()
参数使用一些不寻常的字符串。
有关这两个问题的更多信息,请参见文档。
这样的事情应该起作用:
// define the locales for setlocale() for which we need the daynames
$locales = array(
'en_EN',
'de_DE',
'nl_NL'
// etc...
);
// be aware that setlocale() needs different values on Windows machines
// see the docs on setlocale() for more information
$locales = array(
'english',
'german',
'dutch'
// etc...
);
// let's remember the current local setting
$oldLocale = setlocale( LC_TIME, '0' );
// initialize out result array
$localizedWeekdays = array();
// loop each locale
foreach( $locales as $locale )
{
// create sub result array for this locale
$localizedWeekdays[ $locale ] = array();
// 7 days in a week
for( $i = 0; $i < 7; $i++ )
{
// set the locale on each iteration again
setlocale( LC_TIME, $locale );
// combine strftime() with the nifty strtotime()
$localizedWeekdays[ $locale ][] = strftime( '%A', strtotime( 'next Monday +' . $i . ' days' ) );
// reset the locale for other threads, as a courtesy
setlocale( LC_TIME, $oldLocale );
}
}
// there is your result in a multi-dimensional array
var_dump( $localizedWeekdays );