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
$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);
}
}
answered Jun 21, 2010 at 9:49
Sjoerd
75.9k16 gold badges140 silver badges180 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Jun 21, 2010 at 9:55
Matteo Riva
25.1k13 gold badges75 silver badges105 bronze badges
2 Comments
Gordon
This is
str_replace('a', 'i', 'eval'); ;)Matteo Riva
There Is More Than One Way... oh wait, it was just for fun :)
Explore related questions
See similar questions with these tags.
lang-php