0

I am trying to compare retrieved json data from a database, and there is a nested if statement within the for loop. The problem is that the 'if' statement is only executing once (when it finds the first record in the database), and then it's being skipped in further iterations. I am using PHP and MySQL (for the db).

for ($i=0;$i<count($obj['datalist']);$i++){
    $name[]=$obj['datalist'][$i]['name'];
    if ($name[$i]===$row['user']){ //once it finds the first record, it goes to the 'else' part for the rest of the for loop
    //if ($row['user']==$name[$i]){
        echo "<p class='testclass'>".$name[$i] ." is in the database! ".$i."<br />";
    } else {
        echo "<p class='testclass'>". $name[$i] ." is NOT in the database! ".$i."</p>";
    }
}

Code can be also found here.

4
  • What's weird is that you're simply pushing the name into the $name array without any previously defined indexes and then check for it using $i as an index. You sure you shouldn't be doing it like this: $name[$i]=$obj['datalist'][$i]['name'];? Commented May 6, 2014 at 7:39
  • to be honest, this is the first time i've done anything with json, so i have no idea Commented May 6, 2014 at 7:43
  • Hmm, so you're building an array which you will later output as a JSON string? Commented May 6, 2014 at 9:04
  • Is this problem solved? please let us know Commented May 6, 2014 at 12:27

2 Answers 2

1

Should your code not be this:

$name=$obj['datalist'][$i]['name'];

//if ($name[$i]===$row['user']){
if ($row['user']==$name){

You are already getting the name from the collection, and you want to compare it with your $row isnt?

Sign up to request clarification or add additional context in comments.

Comments

1

You are recreating the same $name in every loop.

you should use this line instead :

$name[$i]=$obj['datalist'][$i]['name'];

Or if you don't need to reuse the $name collection/array then you can simply overwrite it using :

$name = $obj['datalist'][$i]['name'];

and modify your if statement according to this variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.