如何在一个列表中显示同一时间的国家/地区

时间:2017-06-16 12:52:35

标签: php arrays oop datetime

我有这段代码:

   public function parse_timezones_list($timezones = '') {
    global $lang, $core;
    if(!is_array($timezones) || is_empty($timezones)) {
        $timezones = array('UTC', 'Africa/Casablanca', 'Africa/Dakar', 'Africa/Abidjan', 'Europe/Paris', 'Africa/Lagos', 'Africa/Algiers', 'Africa/Tunis', 'Africa/Cairo', 'Asia/Beirut', 'Asia/Amman', 'Africa/Nairobi', 'Asia/Riyadh', 'Asia/Tehran', 'Asia/Dubai', 'Asia/Hong_Kong');
    }
    $gmttime = gmmktime(gmdate('H'), gmdate('i'), gmdate('s'), gmdate('n'), gmdate('d'), gmdate('Y'));
    $timezones_list.='<ul class="list-group">';
    foreach($timezones as $timezone) {
        $timezone_obj = new DateTimeZone($timezone);
        $time_obj = new DateTime('now', $timezone_obj);
        $timezone_city = str_replace('_', ' ', explode('/', $timezone));
        if(empty($timezone_city[1])) {
            $timezone_city[1] = $timezone_city[0];
        }
        $timezones_list .= '<li class="list-group-item">'.$lang->sprint($lang->timecity, date('H:i', $gmttime + $timezone_obj->getOffset($time_obj)), ucwords($timezone_city[1])).'</li>';
    }
    $timezones_list.='</ul>';
    return $timezones_list;
}

所以结果如下:14:45 UTC time 14:45 Casablanca time 14:45 Dakar time 14:45 Abidjan time 16:45 Paris time 15:45 Lagos time 15:45 Algiers time 15:45 Tunis time 16:45 Cairo time

我想表明,对于每一个在同一行中有相同时间的国家/地区,例如我想要这样:14:45 Casablanca time,Dakar time,Abidjan time

谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

不是100%我理解这个问题,但是此代码会将位置分组到各自的时区:

$timezones = array('Africa/Casablanca', 'Africa/Dakar', 'Africa/Abidjan', 'Europe/Paris', 'Africa/Lagos', 'Africa/Algiers', 'Africa/Tunis', 'Africa/Cairo', 'Asia/Beirut', 'Asia/Amman', 'Africa/Nairobi', 'Asia/Riyadh', 'Asia/Tehran', 'Asia/Dubai', 'Asia/Hong_Kong');
$locations = array();
foreach ($timezones as $timezone) {
    $dateTime = new DateTime(); 
    $dateTime->setTimeZone(new DateTimeZone($timezone)); 
    $locations[$dateTime->format('T')][] = $timezone;
}

它在$ locations中创建一个数组,其中包含时区的键和区域的值。输出类似于:

Array
(
    [WET] => Array
        (
            [0] => Africa/Casablanca
        )

    [GMT] => Array
        (
            [0] => Africa/Dakar
            [1] => Africa/Abidjan
        )

    [CEST] => Array
        (
            [0] => Europe/Paris
        )

    [WAT] => Array
        (
            [0] => Africa/Lagos
        )
)