2015-10-05 3 views
0

У меня возникли проблемы с созданием массива JSON. Он должен выглядеть следующим образом:php create response json array

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

Я думаю, что это легко, но я не могу найти правильный путь.

ответ

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

Черт вы были быстрее, вы могли бы описать то, что вы сделали и почему, это улучшило бы этот ответ. – jmattheis

+0

@ Rocky извините.i позаботится о следующем –

+0

работы безупречный! спасибо! надеюсь, что я могу добавить новый массив в массив вопросов самостоятельно;) – markus

0

Array push, push it on end of array. Поэтому результат без ключевых вопросов. вместо:

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