函数不返回 true 或 false(如果它是正确的)



>我正在编写一个函数来检查嵌套键是否存在于 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); 

所以它将返回调用的结果

传入$JSONRequest

json_decode($JSONRequest, true);

编辑:对不起,我第一次弄错了。使用array[0]而不是current()如果您正在移动元素,也许它会产生问题。当然,要var_dump()检查值。

$currentkey = '

data' and end($keyCheckArray) = 'deviceid'。这永远不会返回 true,因此您没有指定返回值,它将返回 null。

两个建议:

  1. 为函数提供所有可能的方法,以结束函数的有效返回值。

  2. 为每个固定结果创建一个变量,如 end($keyCheckArray)。

如果已经测试了您的函数(并出于测试目的对其进行了编辑):

function checkNestedKeysExists($JSONRequest,$keyCheckArray){
  $currentKey = current($keyCheckArray);
  $JSONRequest = array_change_key_case($JSONRequest, CASE_LOWER); 
  $endValue = end($keyCheckArray);
if(array_key_exists($currentKey,$JSONRequest)){
    print 'currentKey = '.$currentKey.", end = ".$endValue."<br>n";
    if($currentKey== $endValue){
        return 'correct';            
    }else { 
        array_shift($keyCheckArray);  
        $p = checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray);
        print "p = ".$p."<br>n";
        //echo "F";
        return $currentKey;
    }    
}
else{
    return false;
}
}

输出如下所示:正确

device_info

数据

我建议你将函数更改为 while 循环。找到请求的结果后,返回 true。

相关内容

最新更新