[英]php create response json array
我在创建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);
我认为这很容易,但是我找不到正确的方法。
$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);
数组推送,将其推送到数组末尾。 因此结果没有关键问题。 代替:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.