0

Helo, i am having a problem with my json, i am having a foreach in a foreach in a for... dont ask why

My problem is that the foreach foreach( $result2 as $rowx ) only returns the last record. the query is ok is working fine it returns 2 fields from database , but only the last is echo'ed.

Any help please.

 if(!$location){
    echo '{"locations":[';
    $query = $db->prepare("SELECT * FROM locations"); 
    $query->execute();
    $result = $query -> fetchAll();
    $num_rows = count($result);
           for ($x = 1; $x < $num_rows; $x++) {
    foreach( $result as $row ) { 
    $qer = "SELECT DISTINCT t.id_temp,f.id_fridge,l.id_location,t.id_sensor,f.denumire AS 'fridge_name',l.name AS 'location_name',l.address AS 'location_address',t.date,t.time,t.temp FROM fridges AS f,locations AS l,temperature AS t WHERE f.fk_location=l.id_location AND f.fk_id_sensor=t.id_sensor AND l.id_location='1' AND t.date='07/05/2015' ORDER BY t.id_temp DESC LIMIT 0,2";

    $query2 = $db->prepare($qer); 
    $query2->execute();
    $result2 = $query2 -> fetchAll();



    echo '{"location_name":"'.$row[1].'","nr_fridges":'.$row[2].',"fridge":';
    foreach( $result2 as $rowx ) { 

    }
    echo '{
    '.$rowx['fridge_name'].'

    }'; 

    echo '}';

    }
        echo "]}";
    exit; 
    }
    }
2
  • Check at json_encode function, it will make debug really easier because in this way, it is really hardly readable Commented May 11, 2015 at 7:26
  • What's the purpose of empty foreach (most inner one)? Commented May 11, 2015 at 7:28

3 Answers 3

2

You have echoes outside the loop.

foreach( $result2 as $rowx ) { 
    echo '{
        '.$rowx['fridge_name'].'
    }'; 

    echo '}';
}

echo "]}";
Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is probably caused by the fact that you are using $rowx['fridge_name'] after the loop instead of inside it:

foreach( $result2 as $rowx ) { 

}
echo '{
'.$rowx['fridge_name'].'

}'; 

should be:

foreach( $result2 as $rowx ) { 
  echo '{
  '.$rowx['fridge_name'].'
  }'; 
}

Also note that now you are not building valid json as an object would need a key - value pair where string values are quoted in double quotes ".

However, you should not build json manually anyway, instead you should build an array of the form you need and at the very end you do:

echo json_encode($your_array);

Comments

0
foreach( $result2 as $rowx ) { //foreach begin

    } //foreach end

your echo is outside the foreach loop.

Try this,

foreach( $result2 as $rowx ) { 
    echo '{
    '.$rowx['fridge_name'].'
    }';
}

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.