【发布时间】:2014-02-26 11:37:10
【问题描述】:
我正在编写一个函数来检查嵌套键是否存在于 JSON 中,但是当代码正确时我卡在了原地,那么它必须返回 true 或 false,但事实并非如此。它返回空值
php函数是
function checkNestedKeysExists($JSONRequest,$keyCheckArray){
$currentKey = current($keyCheckArray);
$JSONRequest = array_change_key_case($JSONRequest, CASE_LOWER);
if(array_key_exists($currentKey,$JSONRequest)){
if($currentKey==end($keyCheckArray)){
return true;
}
else {
array_shift($keyCheckArray);
$this->checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray);
//echo "F";
}
}
else{
return false;
}
}
给定数组是
$keyCheckArray = array('data','device_info','deviceid');
$JSONRequest 是
{
"timestamp": "2014-01-01 11:11:11",
"data": {
"requestid": "bcpcvssi1",
"device_info": {
"os": "Android",
"deviceId": "123123",
"userProfile": {
"email": [
"abc@gmail.com"
],
"gender": "Male",
"age": "19",
"interest": [
"Apple",
"Banana"
]
}
}
}
}
【问题讨论】:
-
需要返回递归函数的输出。
return $this->checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray);. -
感谢@h2ooooooo 它有效!。
-
这是我在回答中给你的第一个建议。
-
@LoekBergman OP 很可能没有意识到他的缺陷,因此“为函数提供所有可能的方法来结束函数一个有效的返回值。”可能没有用对正在进入该语言的人。如果它是如此明显,OP可能会自己完成。 :-)
-
@h2ooooooo:有道理,我以前听过,我有时说话太抽象了。好吧,我希望OP仍然会接受他的建议。如果我从编程一开始就这样做,那么我需要解决的问题就会更少。