我需要检查一个密钥是否存在并返回其值。如果有的话 键可以是带有子键的数组,也可以是带有值的endkey。
$_SESSION['mainKey']['testkey'] = 'value';
var_dump(doesKeyExist('testkey'));
function doesKeyExist($where) {
$parts = explode('/',$where);
$str = '';
for($i = 0,$len = count($parts);$i<$len;$i++) {
$str .= '[\''. $parts[$i] .'\']';
}
$keycheck = '$_SESSION[\'mainKey\']' . $str;
if (isset(${$keycheck})) {
return ${$keycheck};
}
// isset($keycheck) = true, as its non-empty. actual content is not checked
// isset(${$keycheck}) = false, but should be true. ${$var} forces a evaluate content
// isset($_SESSION['mainKey']['testkey']) = true
}
使用PHP 5.3.3。
答案 0 :(得分:2)
不要构建字符串,只需检查循环中是否存在密钥。
例如:
function doesKeyExist($where) {
$parts = explode('/',$where);
$currentPart = $_SESSION['mainKey'];
foreach($parts as $part) {
if (!isset($currentPart[$part])) {
return false;
}
$currentPart = $currentPart[$part];
}
return true;
}
答案 1 :(得分:1)
function getByKeys($keys, $array) {
$value = $array;
foreach (explode('/', $keys) as $key) {
if (isset($value[$key])) {
$value = $value[$key];
} else {
return null;
}
}
return $value;
}
答案 2 :(得分:0)
也许我误解了这个问题,但这似乎是最简单的方法:
function getKey($arr, $key) {
if (array_key_exists($key, $arr)) {
return $arr[$key];
} else {
return false;
}
}
$value = getKey($_SESSION['mainKey'], 'testkey');
答案 3 :(得分:-1)
你应该使用$$ keycheck,而不是$ {$ keycheck}。
最后一种表示法是在字符串中使用变量时(例如“$ {$ keycheck}”)
有关变量变量的更多详细信息,请参阅http://php.net/manual/en/language.variables.variable.php
答案 4 :(得分:-4)
您可能希望使用 eval() php函数。
function doesKeyExist($where) {
$parts = explode('/',$where);
$str = '';
for($i = 0,$len = count($parts);$i<$len;$i++) {
$str .= '["'. $parts[$i] .'"]';
}
eval('$keycheck = $_SESSION["mainKey"]' . $str . ';');
if (isset($keycheck)) {
return $keycheck;
}
}
HTH