0

所以我试图从 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?"}]}
4

2 回答 2

1

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

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)
                    )
            )
        )
    )
);
于 2012-07-16T12:32:37.540 回答
1

选项表怎么样?

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

这样你就可以为你的心内容添加选项

于 2012-07-16T12:34:06.730 回答