开发者

PHP: Split array of strings into multi-dimensional array

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',
);


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜