在php中输出json数组

时间:2012-01-02 22:33:26

标签: php json

我现在有这个json:

{"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"}

我想知道如何输出这个:

{"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"}
}

以下是php中的代码:

while($result=mysql_fetch_array($number, MYSQL_ASSOC)){
        print(json_encode($result));

    }

2 个答案:

答案 0 :(得分:6)

试试这个:

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

答案 1 :(得分:0)

如果我理解你要做的是什么,请获取包含所有行的JSON数据包,然后循环它们以将它们放入数组中,然后对整个数组进行编码:

<?php
  $result = mysql_query($query);
  $out = array('quests' => array());
  while ($row = mysql_fetch_assoc($result)) {
      $out['quests'][] = $row;
  }
  print json_encode($out);
?>