字符串到多维数组路径 [英] String to multidimensional array path

查看:32
本文介绍了字符串到多维数组路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,这里是一小段摘录:

数组 ([专辑] =>大批 ([一个伟大的大世界 - 有没有人在那里] =>大批(...),[ATB - 联系人] =>大批(...),)[流行] =>大批 (...))

我有一个动态路径:

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

解决方案

$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];} 别的 {throw new Exception("路径 $path 无效");}}回声 $value;

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆