使用路径到一个数组项 [英] Using a path to an array item

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

问题描述

有没有用路径或路径元素的数组多维数组中引用一个项目的方法吗? EG。

Is there a way to reference an item within a multidimensional array by using a path or an array of path elements? EG.

$multi = array
(
    'array_1' => array
    (
        'array_2' => array
        (
            'option_1' => 'value_1',
            'option_2' => 'value_2',
        )
    )
);

$path = array('level_1', 'level_2', 'option_1');
$result = $multi[$path];

和有$结果='_1'?

And have $result = 'value_1'?

其原因是,我有搜索THRU $多,并找到我所需要的关键,并返回$路径的递归函数。我知道我可以硬code,从我自己的code中的路径,但我试图使这一可重复使用的,这样我可以编辑$多,功能仍然可以工作。

The reason being, I have a recursive function for searching thru $multi and finding the key I need, and returning the $path. I know i can hard code in the path from my own code but i'm trying to make this reusable so that i can edit the $multi and the function will still work.

推荐答案

有什么内置到PHP这样做,但你可以写一个函数它,使用移动参考:

There's nothing built into PHP to do this but you can write a function for it, using a moving reference:

/**
 * @param string $path path in the form 'item_1.item_2.[...].item_n'
 * @param array $array original array
 */
function &get_from_array($path, &$array)
{
    $current =& $array;
    foreach(explode('.', $path) as $key) {
        $current =& $current[$key];
    }
    return $current;
}

例如:

// get element:
$result = get_from_array('level_1.level_2.option_1', $multi);
echo $result; // --> value_1

$result = 'changed option';
echo $multi['level_1']['level_2']['option_1']; // --> changed_option

我写它的名称从配置文件转换成数组,如果你想通过路径本身像你的榜样阵列,只是离开了爆炸。

I wrote it to convert names from configuration files to arrays, if you want to pass the path itself as an array like in your example, just leave out the explode.

这篇关于使用路径到一个数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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