Reputation: 1506
I am writing a function which checks nested keys if it exists in JSON, but i hav stuck at place when if code is correct then it must return true or false but it is not. it returns null value
php function is
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;
}
}
given array is
$keyCheckArray = array('data','device_info','deviceid');
and $JSONRequest is
{
"timestamp": "2014-01-01 11:11:11",
"data": {
"requestid": "bcpcvssi1",
"device_info": {
"os": "Android",
"deviceId": "123123",
"userProfile": {
"email": [
"[email protected]"
],
"gender": "Male",
"age": "19",
"interest": [
"Apple",
"Banana"
]
}
}
}
}
Upvotes: 0
Views: 155
Reputation: 2195
$currentkey = 'data' and end($keyCheckArray) = 'deviceid'. That will never return true, hence you have no return values specified and it will return null.
two advices:
give the function with every possible way to end the function a valid return value.
create a variable for every fixed outcome like end($keyCheckArray).
If have tested your function (and edited it for testing purposes):
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;
}
}
The output is like this: correct
device_info
data
I suggest you change your function into a while loop. Once you have found the requested result, return true.
Upvotes: 0
Reputation: 604
Modify the line of your code where you make recursive call like following
return $this->checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray);
So it will return the result of the call
Upvotes: 1
Reputation: 698
EDIT: Sorry I got it wrong in first time.
Use array[0]
instead of current()
if you are shifting elements, maybe it is making a problem. And of course, do the var_dump()
to check values.
Upvotes: 0