我在创建JSON数组时遇到了一些麻烦。它应如下所示:
error : false
duellid : 1
questions : [
{ questionid : xx
question : lala
answer : blabla },
{ questionid : xx
question : lala
answer : blabla },
{ questionid : xx
question : lala
answer : blabla }
]
目前问题是在json响应中创建顶部数组问题:
$response["error"] = FALSE;
$duellid = $duell["id"];
$response["duell"] = $duellid;
array_push($return_arr,$response);
$response = array();
$resultquestion = $db->getquestions($rows);
while ($row = mysql_fetch_array($resultquestion)) {
$response["question"]["id"] = $row["id"];
$response["question"]["question"] = $row["question"];
$response["question"]["answer"] = $row["answer"];
$response["question"]["active"] = $row["active"];
$response["question"]["minval"] = $row["minval"];
$response["question"]["maxval"] = $row["maxval"];
array_push($return_arr,$response);
}
echo json_encode($return_arr);
我认为这很容易,但我找不到正确的方法。
答案 0 :(得分:1)
$response = array();
$response["error"] = FALSE;
$duellid = $duell["id"];
$response["duell"] = $duellid;
$resultquestion = $db->getquestions($rows);
$response['questions'] = array();
while ($row = mysql_fetch_array($resultquestion)) {
$result = array(
'questionid' => $row["id"],
'question' => $row["question"],
'answer' => $row["answer"],
'active' => $row["active"],
'minval' => $row["minval"],
'maxval' => $row["maxval"]
);
$response['questions'][] = $result;
}
echo json_encode($response);
答案 1 :(得分:0)
数组推送,将其推送到数组末尾。所以结果没有关键问题。而不是:
array_push($return_arr,$response);
简单地说就是这样:
$response = array('questions'=>array());
$response["error"] = FALSE;
$response["duell"] = $duell["id"];
$resultquestion = $db->getquestions($rows);
while ($row = mysql_fetch_array($resultquestion)) {
$r = array();
$r["id"] = $row["id"];
$r["question"] = $row["question"];
$r["answer"] = $row["answer"];
$r["active"] = $row["active"];
$r["minval"] = $row["minval"];
$r["maxval"] = $row["maxval"];
$response["questions"][] = $r;
// or nicer:
$response["questions"][] = array(
'question' => 'Your question',
'answer' => 'any answer'
);
}
echo json_encode($response);