本文介绍了包含键和关联数组的数组,如何建立关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含path
到另一个数组中的特定值的数组,为了使它更加清楚,这是一个例子.
I have an array which contains the path
to a specific value from an other array, to make it a bit more clear, here is an exemple.
包含要称为$ params的键的数组
My array containing the keys which I'll call $params
Array
(
[0] => paths
[1] => assets
[2] => js
)
这是我的关联数组,我将其称为$ config
And here is my associative array which I'll call $config
Array
(
[paths] => Array
(
[assets] => Array
(
[js] => /assets/js
[css] => /assets/css
)
)
[library] => Array
(
[js] => jQuery
)
)
那么我该如何使用数组1来访问数组2中的值?
So how could I use my array 1 to access the value in my array 2?
我尝试了$config[$params[0]][$params[1]][$params[2]]
,但是效率不高.
I tried $config[$params[0]][$params[1]][$params[2]]
, but it's not efficient at all.
推荐答案
您可以尝试
$path = array(
0 => 'paths',
1 => 'assets',
2 => 'js',
);
$data = array(
'paths' => array(
'assets' => array(
'js' => '/assets/js',
'css' => '/assets/css',
),
),
'library' => array(
'js' => 'jQuery',
),
);
$temp = $data;
foreach($path as $key) {
$temp = $temp[$key];
}
var_dump($temp);
输出
string '/assets/js' (length=10)
这篇关于包含键和关联数组的数组,如何建立关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!