如何按值对以下代码进行排序
$countries = array ('Europe/Rome', 'Europe/Athens', 'America/Tijuana', 'Canada/Atlantic', 'Europe/Amsterdam');
foreach ($countries as $country => $country_offset) {
$offset = timezone_offset_get( new DateTimeZone( $country_offset ), new DateTime() );
echo $offset . '</br>';
}
正如我所理解的,您需要对$offset值进行排序。如果是,则转到以下内容:
$offsets = Array();
$countries = array ('Europe/Rome', 'Europe/Athens', 'America/Tijuana', 'Canada/Atlantic', 'Europe/Amsterdam');
foreach ($countries as $country_offset) {
$offset = timezone_offset_get( new DateTimeZone( $country_offset ), new DateTime() );
array_push($offsets, $offset);
}
asort($offsets);
foreach($offsets as $offset) {
echo $offset . "<br />";
}
正如您可能看到的,您必须将获得的每个$offset推送到一个新数组($offset,复数)中,然后对其进行排序
此外,你的建筑
foreach ($countries as $country => $country_offset)
缺少一点:这里的$country将是$countries数组的数字索引,您在代码的其余部分中不会使用它。然后忘记它,只使用元素,就像在中一样
foreach ($countries as $country_offset)
希望它能有所帮助!
OBS:要包括密钥,正如你所要求的,你可以做:
asort($offsets);
$keys = array_keys($offsets);
foreach($keys as $key) {
echo $offsets[$key] . $key . "<br />";
}
功能asort保留了密钥,所以如果你想要区域的名称,你可以进行
asort($offsets);
$keys = array_keys($offsets);
foreach($keys as $key) {
echo $offsets[$key] . " - " . $countries[$key] . "<br />";
}