如何获取数组中键的名称

How to get the name of a key in array

这听起来很简单,但我做不到。我正在尝试对具有相同值的键进行分组。我可以获得钥匙编号,但无法获得钥匙的名称。即 "London, Berlin"。 这是我的代码:

$countries = array (
   'London' => 'Europe/London',
   'Istanbul' => 'Europe/Istanbul',
   'Rome' => 'Europe/Rome',
   'Berlin' => 'Europe/Berlin',
   'Athens' => 'Europe/Athens',
);


$offsets = Array();
foreach ($countries as $country_offset) {
   $offset = timezone_offset_get( new DateTimeZone( $country_offset ), new DateTime() );

   array_push($offsets, $offset);
}

$result = array_unique($offsets);
asort($result);

$keys = array_keys($result);
foreach($keys as $key) {
   $numb = array_keys($offsets, $offsets[$key]);

   echo $offsets[$key] . ' - ' . implode(', ', $numb ) . '<br>';
}

我建议先创建包含所需键的完整信息数组分组,而不是创建映射原始输入键的演示文稿。

想法:

$offsets = array(); // initialize
foreach($countries as $key => $country_offset) { // grouping
    $offset = timezone_offset_get( new DateTimeZone( $country_offset ), new DateTime() );
    $offsets[$offset][] = array(
        'name'      => $key, // include me instead!
        'offset'    => $offset,
        'timezome'  => $country_offset,
    );
}
ksort($offsets); // sort

这里重要的一点是,使用偏移量作为键将它们分组在一个容器中:

$offsets[$offset][] = array(
//       ^ reassignment grouping using the offset as key

然后,在您的演示文稿中,决定您想要什么:

// presentation
foreach($offsets as $offset => $info) {
    echo $offset . ' - ';
    $temp = array();
    foreach($info as $t) {
        $temp[] = $t['name'];
    }
    echo implode(', ', $temp);
    echo '<br/>';
}

如果array_column可用,就用它:

foreach($offsets as $offset => $info) {
    echo $offset . ' - ' . implode(', ', array_column($info, 'name')) . '<br/>';
}

Sample Output

 <?php
$countries = array (
   'London' => 'Europe/London',
   'Istanbul' => 'Europe/Istanbul',
   'Rome' => 'Europe/Rome',
   'Berlin' => 'Europe/Berlin',
   'Athens' => 'Europe/Athens',
);

$out=array();
foreach ($countries as $country_offset=>$c) {
   $offset = timezone_offset_get( new DateTimeZone( $c ), new DateTime() );


$out[$offset][]=$country_offset;
}
//print_r($out);

foreach($out as $x=>$y){

echo $x.': '.implode(',',$y).'<br>';
}

//输出:

3600:伦敦
10800: 伊斯坦布尔,雅典
7200: 罗马,柏林