找到仅具有与键的字符串嵌套阵列内的值 [英] Finding a value inside a nested array having only a string with the keys
问题描述
我有一个包含一些设置,看起来像一个阵列基本上是这样的:
I have one array that contains some settings that looks like basically like this:
$defaults = array(
'variable' => 'value',
'thearray' => array(
'foo' => 'bar'
'myvar' => array('morevars' => 'morevalues');
);
);
在另一个文件中,我得到的第一级密钥字符串,它的童车,以检查是否有连接到它的值。使用上面的数组,我会得到这样的:
On another file, i get a string with the first level key and it's childs to check if there is a value attached to it. Using the array above, i'd get something like this:
$option = "thearray['myvar']['morevars']";
我需要保持这个字符串格式类似于上面,因为我还需要将它传递到保存到数据库中,并让它在一个阵列的格式就派上用场了另一种功能。
I need to keep this string with a similar format to the above because I also need to pass it to another function that saves to a database and having it in an array's format comes in handy.
我的问题是,在数组和上面的字符串,我怎么能检查数组中给定的关键点的,存及其价值? array_key_exists似乎不低于第一级的工作
My question is, having the array and the string above, how can i check for both, existance and value of the given key inside the array? array_key_exists doesn't seem to work below the first level.
推荐答案
您可以使用一个简单的函数解析您的钥匙串并检查像数组:
You could use a simple function to parse your key-string and examine the array like:
function array_deep_exists($array, $key)
{
$keys = preg_split("/'\\]|\\['/", $key, NULL, PREG_SPLIT_NO_EMPTY);
foreach ($keys as $key)
{
if ( ! array_key_exists($key, $array))
{
return false;
}
$array = $array[$key];
}
return true;
}
// Example usage
$defaults = array(
'variable' => 'value',
'thearray' => array(
'foo' => 'bar',
'myvar' => array('morevars' => 'morevalues')
)
);
$option = "thearray['myvar']['morevars']";
$exists = array_deep_exists($defaults, $option);
var_dump($exists); // bool(true)
最后,得到的值(如果存在)返回 $阵列
其中,上述回报率真正
。
请注意,如果您的数组中可能包含假
,返回值那么当你必须要小心从一个成功的假值差异无匹配值。
Note that if your array might contain false
, then when returning the value you'll have to be careful to differentiate no-matching-value from a successful false value.
这篇关于找到仅具有与键的字符串嵌套阵列内的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!