如果函数正确,则函数不返回true或false

时间:2014-02-26 11:37:11

标签: php json

我正在编写一个函数来检查嵌套密钥是否存在于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"
            ]
        }
    }
}
}

4 个答案:

答案 0 :(得分:1)

修改您执行递归调用的代码行,如下所示

return $this->checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray); 

因此它会返回调用的结果

答案 1 :(得分:0)

中传递$ JSONRequest
json_decode($JSONRequest, true);

答案 2 :(得分:0)

编辑:对不起我第一次弄错了。 如果要转换元素,请使用array[0]代替current(),这可能会产生问题。当然,请var_dump()检查值。

答案 3 :(得分:0)

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

两个建议:

  1. 为函数提供各种可能的方法来结束函数的有效返回值。

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

  3. 如果已经测试了您的功能(并为测试目的进行了编辑):

    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。

相关问题