【发布时间】:2011-08-30 15:05:32
【问题描述】:
可能重复:
Check if a “run-time” multidimensional array key exists
嗨,
我有一个多维数组。我需要一个函数来检查指定的键是否存在,如果没有设置值。
我们来看看这个数组
$config['lib']['template']['engine'] = false;
当我调用时,函数不应将值更新为 true:
checkAndSetKey('lib template engine',true);
//> Checks if isset $config['lib']['template']['engine'] and if not isset $config['lib']['template']['engine'] = true;
请注意,我的数组不仅是 3 维的。即使只有一维,它也应该能够检查和设置:
checkAndSetKey('genericSetting',true);
//> In this considering there isn't any $c['genericSetting'] the function set the key to true;
目前我正在使用糟糕的 eval 代码,我想听听建议:)
要动态检查密钥是否存在,可以使用以下代码:
$array = $config;
$keys=explode(' ',$argument1);
foreach($keys as $v) {
if (!array_key_exists($v,$array)) {
//> [todo!] the current key doens't exist now we should set the value
}
$array = &$array[$v];
}
【问题讨论】:
-
很有用:stackoverflow.com/questions/6088115/… 这看起来不是更改设置的好方法。
-
那是我自己的问题。而且他们不是 DUP,因为这个问题只是为了看看它是否被设置为不设置。下次阅读更好
-
我猜如果 jeff 关闭它我会说什么 xD
标签: php