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
re1man
2,37711 gold badges38 silver badges55 bronze badges
-
Did you try something ? It sounds pretty easy to do...ldiqual– ldiqual2012年01月02日 22:36:38 +00:00Commented Jan 2, 2012 at 22:36
-
1Spend some time here: php.net/manual/en/ref.json.phpThe Nail– The Nail2012年01月02日 22:38:37 +00:00Commented 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.James– James2012年01月02日 22:41:09 +00:00Commented 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.Gabriel Santos– Gabriel Santos2012年01月02日 22:50:05 +00:00Commented Jan 2, 2012 at 22:50
2 Answers 2
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
ruX
7,5123 gold badges42 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Umbrella
4,8083 gold badges24 silver badges32 bronze badges
3 Comments
Gabriel Santos
Change
$out[] = $row to $out['quests'][] = $rowGabriel Santos
Wrong again. need to be exactly:
$out['quests'][] = $row;. If are only $out['quests'] = $row;, every time you array will be ovewrited.Umbrella
I'm sure there's an expression for the experience of having such an obvious mistake caught, twice, but I can't place it.
lang-php