所以我试图从 MySQL 编码为 JSON,我需要 [pagenumber][id,type,description][answerid,answerdescription] 格式。这样做的目的是读取 javascript 文件中的数据,该文件将为我生成多步投票。
我将尝试在此处绘制一个伪代码,说明我希望它的外观:
{"pages":
[{1:
[{"id":1,"text":"U mad?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"},
{"opt_id":3,"option":"perhaps","answer:''"}]},
{"id":2,"text":"Got it?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"}]
}]
},
{2:
[{"id":3,"text":"Help me?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"},
{"opt_id":3,"option":"perhaps","answer:''"}]},
{"id":4,"text":"Please?","options":
[{"opt_id":1,"option":"yes","answer:''"},
{"opt_id":2,"option":"no","answer:''"}]
}]
}]
}
这是我到目前为止得到的,但我似乎想不出一种方法来添加第三个“维度”,我想要一个 [id => (int), description => (string)] 的数组对每个问题。每个问题都需要空间来容纳与其相关的多个答案。answers/options 数组中的最后一列是文本字符串(大多数答案由 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?"}]}