0

I have an array of timezones:

$timezones = array(
    'Africa/Abidjan',
    'Africa/Accra',
    ...
    'America/Argentina/Buenos_Aires',
    'America/Argentina/Catamarca',
    ...
    'Pacific/Wallis',
    'UTC',
);

How can I easiest split this array so that I get one like this:

$timezones = array(
    'Africa' => array('Abidjan', 'Accra', ... ),
    'America' => array(..., 'Argentina' => array('Buenos_Aires', 'Catamarca', ...), ...),
    ...
    'Pacific' => array(..., 'Wallis'),
    'UTC',
);

2 Answers 2

3
$splitted = array();
foreach ($timezones as $timezone)
{
    $items = explode('/', $timezone);
    add_to_array($splitted, $items);
}
print_r($splitted);

function add_to_array(& $destination, $values)
{
    if (count($values) == 1)
    {
        $destination[] = $values[0];
    }
    else
    {
        $first = array_shift($values);
        add_to_array($destination[$first], $values);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Non recursive hackish version using eval():

$output = array();

foreach ( $timezones as $zone ) {
    if ( strpos($zone, '/') !== FALSE ) {
        $str = preg_replace('#/([^/]+)$#', "'][] = '$1';", $zone);
        $str = str_replace('/', "']['", $str);
        $str = '$output[\''.$str;
        eval($str);
    } else {
        $output[$zone] = '';
    }
}
print_r($output);

2 Comments

This is str_replace('a', 'i', 'eval'); ;)
There Is More Than One Way... oh wait, it was just for fun :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.