2014-01-27 128 views
1

我有一个多维数组,这里是一个小摘录:字符串多维数组路径

Array (
    [Albums] => Array (
     [A Great Big World - Is There Anybody Out There] => Array(...), 
     [ATB - Contact] => Array(...), 
    ) 
    [Pop] => Array (...) 
) 

而且我有一个动态的路径:

/albums/a_great_big_world_-_is_there_anybody_out_there 

什么是检索的最佳方式(在这个例子中)$arr["albums"]["A Great Big World - Is There Anybody Out There"]

请注意它应该是动态的,因为在这个例子中嵌套可以比2层更深。

编辑

下面是我用它来创建用于URL简单的字符串函数:

function formatURL($url) { 
    return preg_replace('/__+/', '_', preg_replace('/[^a-z0-9_\s-]/', "", strtolower(str_replace(" ", "_", $url)))); 
} 

回答

0
$array = array(...); 
$path = '/albums/a_great_big_world_-_is_there_anybody_out_there'; 

$value = $array; 
foreach (explode('/', trim($path, '/')) as $key) { 
    if (isset($value[$key]) && is_array($value[$key])) { 
     $value = $value[$key]; 
    } else { 
     throw new Exception("Path $path is invalid"); 
    } 
} 

echo $value; 
+0

这个循环的作品,但在我的阵列的孩子是不是叫'/albums/a_great_big_world _-_ is_there_anybody_out_there',它是'/相册/一个伟大的大世界 - 有没有人在那里。任何方式来轻松解决这个问题,或者我更好地重写数组创建? –

+1

嗯,是的,没有明显的方法来将一个较低的下划线的弦变成一个套弦。如果你*有*显而易见的方式,去做吧。或者,如果您有一台发电机,可以将套管间距的弦线转换为下部箱体的下弦弦线,则可以使用其他方法。但是坚持使用相同的独特IDs总是比尝试匹配两个不匹配的东西更好的选择。重写你的数组。 – deceze

+0

是的,我想我会在我的主帖中使用'formatURL'函数。谢谢您的帮助! –