2

I have this json currently :

{"quest_id":"1","quest_title":"Buy 3 pints of draft and a large pizza and then get desert","quest_price":"15","quest_points":"100"}{"quest_id":"2","quest_title":"Hello WOrld","quest_price":"50","quest_points":"10"}

I was wondering how I could output this :

{"quests": {"quest_id":"1","quest_title":"Buy 3 pints of draft and a large pizza and then get desert","quest_price":"15","quest_points":"100"}{"quest_id":"2","quest_title":"Hello WOrld","quest_price":"50","quest_points":"10"}
}

Here is the code in php:

while($result=mysql_fetch_array($number, MYSQL_ASSOC)){
 print(json_encode($result));
 }
asked Jan 2, 2012 at 22:33
4
  • Did you try something ? It sounds pretty easy to do... Commented Jan 2, 2012 at 22:36
  • 1
    Spend some time here: php.net/manual/en/ref.json.php Commented Jan 2, 2012 at 22:38
  • your 2nd bit of JSON is not actually valid. You need to have the 2 quests in a list or something like that. Commented Jan 2, 2012 at 22:41
  • You want a done job? I think the best option to learn are the PHP manual, as @TheNail have writed above. Commented Jan 2, 2012 at 22:50

2 Answers 2

7

Try this:

$result = array('quests' => array());
while($row = mysql_fetch_array($number, MYSQL_ASSOC)){
 $result['quests'][] = $row
}
echo json_encode($result);
answered Jan 2, 2012 at 22:40
Sign up to request clarification or add additional context in comments.

Comments

0

If I understand correctly what you are trying to do, get a JSON packet with all the rows, then loop over them to put them in an array, then encode the whole array:

<?php
 $result = mysql_query($query);
 $out = array('quests' => array());
 while ($row = mysql_fetch_assoc($result)) {
 $out['quests'][] = $row;
 }
 print json_encode($out);
?>
answered Jan 2, 2012 at 22:44

3 Comments

Change $out[] = $row to $out['quests'][] = $row
Wrong again. need to be exactly: $out['quests'][] = $row;. If are only $out['quests'] = $row;, every time you array will be ovewrited.
I'm sure there's an expression for the experience of having such an obvious mistake caught, twice, but I can't place it.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.