字符串多维数组路径 [英] String to multidimensional array path
本文介绍了字符串多维数组路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多维数组,这里是一个小的摘录:
阵列(
[相册] =>阵列(
[广阔天地 - 有没有人在这里] =>阵列(...)
[ATB - 联系方式] =>阵列(...)
)
[流行] =>阵列(...)
)
和我有一个动态的路径:
/专辑/ a_great_big_world _-_ is_there_anybody_out_there
什么是检索的值(在这个例子中) $改编[专辑]的最佳方法[广阔天地 - 有没有人在那里]
?
请注意,它应该是动态的,因为嵌套可以比本例中的2级去更深
修改
下面是函数我用它来创建用于URL一个简单的字符串:
函数formatURL($网址){
返回preg_replace('/ __ + /','_',preg_replace('/ [^ A-Z0-9 _ \\ S - ] /,,用strtolower(str_replace函数(,_ $网址))));
}
解决方案
$阵列=阵列(...);
$ PATH =/专辑/ a_great_big_world _-_ is_there_anybody_out_there';$值= $阵列;
的foreach(爆炸('/',修剪($路径,'/'))为$键){
如果(使用isset($价值[$关键])及和放大器; is_array($价值[$关键])){
$价值= $值[$关键];
}其他{
抛出新的异常(路径$路径无效);
}
}回声$价值;
I have a multidimensional array, here is a small excerpt:
Array (
[Albums] => Array (
[A Great Big World - Is There Anybody Out There] => Array(...),
[ATB - Contact] => Array(...),
)
[Pop] => Array (...)
)
And I have a dynamic path:
/albums/a_great_big_world_-_is_there_anybody_out_there
What would be the best way to retrieve the value of (in this example) $arr["albums"]["A Great Big World - Is There Anybody Out There"]
?
Please note that it should be dynamic, since the nesting can go deeper than the 2 levels in this example.
EDIT
Here is the function I use to create a simple string for the 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;
这篇关于字符串多维数组路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文