简体   繁体   中英

PHP: Sorting inside foreach

How can i sort by value the following code

$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>';
}

As I understood things, you need to sort the $offset values. If so, then to the following:

$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 />";
}

As you may see, you must push each $offset obtained into a new array ($offsets, in plural) and then sort it.

Besides, your construction

foreach ($countries as $country => $country_offset)

is missing a point: $country here will be the numeric index of $countries array, which you don't use in the rest of your code. Then just forget it and work just with the elements, as in

foreach ($countries as $country_offset) 

Hope it helps!

OBS: To include the key, as you asked, you could do:

asort($offsets);
$keys = array_keys($offsets);
foreach($keys as $key) {
    echo $offsets[$key] . $key . "<br />";
}

Function asort preserves the keys, so if you want the names of the zones you may do

asort($offsets);
$keys = array_keys($offsets);
foreach($keys as $key) {
    echo $offsets[$key] . " - " . $countries[$key] . "<br />";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM