Encoding Json from MySQL

Encoding Json from MySQL

本文关键字:MySQL from Json Encoding      更新时间:2023-10-05

所以我试图从MySQL编码到JSON,我需要它采用[pagenumber][id,type,description][answerid,answerdescription]格式。这样做的目的是读取javascript文件中的数据,该文件将为我生成一个多步骤轮询

我将尝试绘制一个伪代码,说明我希望它在这里的样子:

{"pages":
  [{1:
    [{"id":1,"text":"U mad?","options":
      [{"opt_id":1,"option":"yes","answerswer:''"},
       {"opt_id":2,"option":"no","answerswer:''"},
       {"opt_id":3,"option":"perhaps","answerswer:''"}]},
       {"id":2,"text":"Got it?","options":
    [{"opt_id":1,"option":"yes","answerswer:''"},
       {"opt_id":2,"option":"no","answerswer:''"}]
    }]
   },
   {2:
    [{"id":3,"text":"Help me?","options":
     [{"opt_id":1,"option":"yes","answerswer:''"},
       {"opt_id":2,"option":"no","answerswer:''"},
       {"opt_id":3,"option":"perhaps","answerswer:''"}]},
     {"id":4,"text":"Please?","options":
      [{"opt_id":1,"option":"yes","answerswer:''"},
       {"opt_id":2,"option":"no","answerswer:''"}]
    }]
  }]
}   

这就是我到目前为止所得到的,但我似乎想不出一种方法来添加第三个"维度",我希望每个问题都附加一个[id=>(int),description=>(string)]数组。每个问题都需要几个与之相关的答案。答案/选项数组中的最后一列用于文本字符串(大多数答案由ID号回答,但有些是需要完整字符串的文本区域)。这可能不需要,因为我可能可以通过序列化将表单结果发回。

$rows = array();
while($r = mysql_fetch_assoc($sth)) 
{
    $Qid = $r['id']; 
    $page=$r['page']; 
    $type=$r['type']; 
    $Qdesc=$r['description'];
    $rows[$page][] = array(
                    'id' => $Qid,
                    'type' => $type,
                    'description' => $Qdesc);
}

结果如下(前3页)。

{
"1":[
  {"id":"2","type":"1","description":"U mad?"},
  {"id":"3","type":"1","description":"Got it?"},
  {"id":"4","type":"1","description":"Help me?"}],
"2":[
  {"id":"5","type":"1","description":"Please?"},
  {"id":"6","type":"1","description":"Any clues?"}],
"3":[
  {"id":"7","type":"2","description":"Foobar?"}]}

选项表怎么样?

id, option, answer
1, yes, ''
2, no, ''
3, perhaps, ''

(你的答案数据总是空的,所以为了一致性,我把它包括在内)

然后,对于每个问题,你都会有一个选项字段,其中"1,2,3"代表所有选项,"1,2"代表是/否等。

要实现这一点,您可以:-

$options=array();
if(!empty($r['options']))
{
    $sql="SELECT * FROM options_table WHERE id IN (".$r['options'].")";
    $result=mysql_query($sql);
    while($row=mysql_fetch_assoc($result){
       $options[]=$row;
    }
}
$rows[$page][] = array(
                'id' => $Qid,
                'type' => $type,
                'description' => $Qdesc,
                'options'=>$options);

通过这种方式,您可以将选项添加到您的心脏内容

这不是一个完整的答案,但为了帮助您开始,您可以使用:

json_encode(array("pages" => array(1 => $row1, 2=>$row2)));

通常,您可以在另一个array(..)中使用array(..)来实现多级嵌套。类似:

json_encode(
    array(
        $item1,
        $item2,
        array(
            "key1" => array(
                    1,
                    2,
                    array(
                        "inKey1" => array(4,5,6)
                    )
            )
        )
    )
);