我有一个多维数组,这里有一个小摘录:
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 :(得分: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;