本文介绍了动态访问多维数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找(或创建)一个函数.我有一个多维数组:
I'm trying to find (or create) a function. I have a multidimensional array:
$data_arr = [
"a" => [
"aa" => "abfoo",
"ab" => [
"aba" => "abafoo",
"abb" => "abbfoo",
"abc" => "abcfoo"
],
"ac" => "acfoo"
],
"b" => [
"ba" => "bafoo",
"bb" => "bbfoo",
"bc" => "bcfoo"
],
"c" => [
"ca" => "cafoo",
"cb" => "cbfoo",
"cc" => "ccfoo"
]
];
我想使用一维数组访问一个值,如下所示:
And I want to access a value using a single-dimentional array, like this:
$data_arr_call = ["a", "ab", "abc"];
someFunction( $data_arr, $data_arr_call ); // should return "abcfoo"
似乎已经有一种用于此类事物的函数,我只是不知道要搜索什么.
This seems like there's probably already a function for this type of thing, I just don't know what to search for.
推荐答案
尝试一下
function flatCall($data_arr, $data_arr_call){
$current = $data_arr;
foreach($data_arr_call as $key){
$current = $current[$key];
}
return $current;
}
OP的解释:
$current
变量被迭代建立,如下所示:
OP's Explanation:
The $current
variable gets iteratively built up, like so:
flatCall($data_arr, ['a','ab','abc']);
1st iteration: $current = $data_arr['a'];
2nd iteration: $current = $data_arr['a']['ab'];
3rd iteration: $current = $data_arr['a']['ab']['abc'];
您还可以在每次迭代中执行if ( isset($current) ) ...
来提供错误检查.
You could also do if ( isset($current) ) ...
in each iteration to provide an error-check.
这篇关于动态访问多维数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!