Search code examples
phparraysimplodearray-uniquearray-key

How to get the name of a key in array


This sounds quite simple, but i can't make it work. I'm trying to group keys with same value. I can get the key number but i cant get the name of the Key. i.e "London, Berlin". This is my code:

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

Solution

  • I'd suggest just create the full info array grouping first that includes the key that you want, instead of creating the presentation mapping the key of the original input.

    Idea:

    $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
    

    The important bit here is that, group them inside a container using the offset as your key:

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

    Then, in your presentation, decide what you want:

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

    If array_column is available, just use it:

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

    Sample Output