re1man
re1man

Reputation: 2377

output json array in php

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));

    }

Upvotes: 2

Views: 5053

Answers (2)

ruX
ruX

Reputation: 7472

Try this:

$result = array('quests' => array());
while($row = mysql_fetch_array($number, MYSQL_ASSOC)){
    $result['quests'][] = $row
}
echo json_encode($result);

Upvotes: 7

Umbrella
Umbrella

Reputation: 4788

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);
?>

Upvotes: 0

Related Questions