我有一个多维数组,这是一个小摘录:
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"]
的值是什么?
请注意,它应该是动态的,因为嵌套可以比此示例的两个级别更深。
编辑
这是我用来为URL创建一个简单字符串的功能:
function formatURL($url) {
return preg_replace('/__+/', '_', preg_replace('/[^a-z0-9_s-]/', "", strtolower(str_replace(" ", "_", $url))));
}
$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;