簡體   English   中英

PHP創建響應JSON數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM