2017-12-30 20 views
1

dies ist mein Code:Wie macht man json_encode immer als JSON Array zurück?

$db = connect_mysqli(); 

    $response = array(); 

    $sql = "SELECT * FROM questions ORDER BY RAND()"; 
    $result = $db->query($sql); 

    while($row = $result->fetch_array(MYSQL_ASSOC)) 
    { 
    $response['answers'][$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null); 
    } 

    echo json_encode($response); 

Und das ist die Antwort:

{ 
    answers: { 
    1: { 
     question_id: "1", 
     option_id: null 
    }, 
    2: { 
     question_id: "2", 
     option_id: null 
    }, 
    3: { 
     question_id: "3", 
     option_id: null 
    }, 
    4: { 
     question_id: "4", 
     option_id: null 
    } 
    } 
} 

Wie die Antwort immer wieder zurückkehren JSON Array machen? nicht JSON Objekt wie das. Manchmal gibt die Antwort JSON Array zurück und gibt JSON Object zurück. Ich möchte alle Antwort auf JSON Array.

So soll es so sein:

$response['answers'][] = array('question_id'=>$row['id'], 'option_id'=>null); 

Das Problem:

{ 
    answers: [ 
    1: { 
     question_id: "1", 
     option_id: null 
    }, 
    2: { 
     question_id: "2", 
     option_id: null 
    }, 
    3: { 
     question_id: "3", 
     option_id: null 
    }, 
    4: { 
     question_id: "4", 
     option_id: null 
    } 
    ] 
} 
+0

Try Änderung '$ response [ 'Antworten'] [$ row [ 'id']]' auf '$ response [ 'Antworten'] []' –

+0

ich brauche dies als Schlüssel $ response [ 'Antworten '] [$ row [' id ']] @MrHery –

+0

Dann versuchen, aus der Datenbank als ein Objekt, nicht als Array abrufen. –

Antwort

1

macht es Ihnen

$response = json_encode($response); 
helfen soll
+0

Ich habe bereits "Json_encode" in meinem Code –

1
$response['answers'][$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null); 

Diese vorherige Zeile geändert werden kommt von der Tatsache, dass du nicht starst t das Array mit einem Index von 0.

+0

Ich brauche diese $ Antwort ['Antworten'] [$ Zeile ['ID']] als Schlüssel –

+0

Wenn Sie einen Schlüssel benötigen, ist es ein Objekt, kein Array, Sie brauchen. Arrays beginnen immer mit einem Nullindex und gehen von dort aus hoch. –

+0

Hmm, wie kann ich es dann zeigen? Wenn ein JSON-Array antwortet [1] .options_id, wie für ein JSON-Objekt? –

1

Wirf die $row['id'] als Zeichenfolge, um das gewünschte Ergebnis zu erhalten.

$db = connect_mysqli(); 

$response = array(); 

$sql = "SELECT * FROM questions ORDER BY RAND()"; 
$result = $db->query($sql); 

while($row = $result->fetch_array(MYSQL_ASSOC)) 
{ 
    $response['answers'][(string)$row['id']] = array('question_id'=>$row['id'], 'option_id'=>null); 
} 

echo json_encode($response); 
+0

Nein, es ist immer noch wie zuvor :( –

+0

@DimasAdiAndrea bitte validieren Sie die JSON, die Sie erwarten. –

+0

Wie kann ich das bestätigen? Es tut mir leid, ich lerne immer noch : D –