访问多维数组通过字符串分隔符 [英] Access multidimensional array by string with delimiter

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

问题描述

假设我有一个多维数组像这样的事情:

suppose i have a multidimensional array like something like this:

<?php

$array = array("test1" => array("test2" => array("test3" => 1)), ... foo1 = array("foo2" => 2));

?>

我想通过传递像test1.test2.test3一个字符串的函数,通过调用数组元素访问数组元素。我可以使用的eval() [] (呼叫 $阵列替换字符串[ 测试2] [TEST3] ...),但我不知道是否有不同的更坚实的方式在调用数组元素,而无需通过其所有的深度遍历或使用的eval()

i want to access an array element by passing a string like "test1.test2.test3" to a function which in turn calls the array element. I could use eval() by replacing the string with [] (calling $array["test2]["test3"] ...) but i wonder if there is a different more solid approach in calling a array element without traversing through all of its depth or use eval().

推荐答案

您可以使用

function get_multi($arr, $str) {
    foreach (explode('.', $str) as $key) {
        if (!array_key_exists($arr, $key)) {
            return NULL; 
        }
        $arr = $arr[$key];
    }

    return $arr;
}

这篇关于访问多维数组通过字符串分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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