2017-08-04 15 views
-1

在我的PHP文件我有代碼包括:爲什麼我的JSON數組在PHP中無法在我的Android應用程序中正確打印?

while ($row = $result->fetch_assoc()) { 

    //make an array called $results 
    $results = array(); 

    $results[] = array(
    'contact_phonenumber' => $row['username'], 
     ); 


    $json2 = json_encode($results); 
    //this is the response which we want in the Android app 
    echo $json2; 

而在我的Android應用程序,我有:

public void onResponse(String response) { 
    //print the JSON Array from the php file 
    System.out.println("the jsonarray is : " + response; 

response當我打印,我得到的格式爲:

[{"contact_phonenumber":"+11111"}][{"contact_phonenumber":"+22222"}][{"contact_phonenumber":"+33333"}][{"contact_phonenumber":"+44444"}][{"contact_phonenumber":"+55555"}] 

但不應該是格式? :

[{"contact_phonenumber":"+11111"}, {"contact_phonenumber":"+22222"},{"contact_phonenumber":"+33333"}, {"contact_phonenumber":"+44444"},{"contact_phonenumber":"+55555"}] 

我該如何實現這個目標?

+1

你不是創造一個合適的JSON。你正在創建多個json字符串。 –

回答

1

試試這個:

$result = []; 
while ($row = $result->fetch_assoc()) { 
    array_push(['contact_phonenumber' => $row['username']], $result); 
} 
$json2 = json_encode($result); 
//this is the response which we want in the Android app 
echo $json2; 
+0

@MagnusEriksson哈哈似乎是最簡單的方法,它只是讓事情變得更清晰。已更新答案以包含您的評論。 – DrRoach

+0

在我的問題$結果和$結果是兩個不同的東西。在我的Android logcat中,我沒有得到任何數據,只是消息'只有變量可以通過引用傳遞給第66行的filename.php,'array_push(['contact_phonenumber'=> $ row ['username']], $結果);」你知道這裏有什麼問題嗎? – CHarris

相關問題