我从php&中获取记录将它们保存在关联数组中。我想创建一个像这样的json格式
{
"contacts": [
{
"qid": "c201",
"question": "what is your name?,
},
{
"qid": "c202",
"question": "what is your age?
},
]}
我正在使用以下代码来获取php中的数据
<?
$response = array();
require("dbconfig.php");
$sql_get = 'SELECT qquesid,question FROM qhistory_data';
$retval = mysql_query( $sql_get, $conn );
if(!$retval )
{
$response["success"] = 0;
$response["message"]= mysql_error();
echo json_encode($response);
}
else
{
$num_rows=mysql_num_rows($retval);
if($num_rows>=0)
{
$i=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$result_array[]= $row['question'];
$result_id[]=$row['qquesid'];
}
答案 0 :(得分:1)
如果你想以你提到的形式获取数组,你必须在执行json_encode之前相应地解析它:
$result = array("contacts" => array());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
$result["contacts"][]= array("qid" => $row['qquesid'], "question" =>$row['question']);
}
echo json_encode($result);