2016-03-07 96 views
0
while循環創建一個JSONArray

我將派出數組到Java爲了填充一個ListView,我怎麼得到下面的代碼輸出數組?:在PHP中使用

<?php 

$user = 'root'; 
$pass = ''; 
$db = 'uopuser'; 

$con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect'); 


$statement = mysqli_prepare($con, 'SELECT * FROM society'); 
mysqli_stmt_execute($statement); 

mysqli_stmt_store_result($statement); 
mysqli_stmt_bind_result($statement, $society_id, $name, $email, $description); 

$society = array(); 

while(mysqli_stmt_fetch($statement)){ 
    $society['society_id'] = $society_id; 
    $society['name'] = $name; 
    $society['email'] = $email; 
    $society['description'] = $description; 
    echo json_encode($society); 
} 

echo json_encode($society); 

mysqli_stmt_close($statement); 

mysqli_close($con); 

?> 

而不是:

{"society_id":1,"name":"TestName1","email":"[email protected]","description":"TestDes1"} 
{"society_id":2,"name":"TestName2","email":"[email protected]","description":"TestDes2"} 
{"society_id":3,"name":"TestName3","email":"[email protected]","description":"TestDes3"} 

我發表了這篇文章之前看過有關互聯網,但我很困惑!感謝任何人提前。

+0

你可以這樣做:$ societies = array(); $ societies.push($社會);回聲json_encode($社會); 將$社會推送到循環內部的$ societies數組中,並在此循環之外進行編碼。 –

回答

1

如果你想要一個數組,你會走得太遠,並且還缺少一個步驟。你在while函數中創建了一個數組,但是你不需要使用json_encode,除非你將它傳遞給需要它的json格式的東西。要製作一個大陣列,只需創建另一個陣列:

$society = array(); 

while(mysqli_stmt_fetch($statement)){ 
    $new_soc = array(); 
    $new_soc['society_id'] = $society_id; 
    $new_soc['name'] = $name; 
    $new_soc['email'] = $email; 
    $new_soc['description'] = $description; 
    //$new_soc is now a single array. You add it to the larger array next 
    $society[] = $new_soc; 
} 

現在您可以做任何您需要做的事情來處理大型社會陣列。

+0

也許我應該提到,我會將它傳遞給Java以填充ListView。 – kmil

+0

完成while語句後,您可以在$ society上執行json_encode,它將包含所有結果。 – aynber

0

如果你只是想要一個數組形式的輸出,那麼你爲什麼要編碼爲JSON?您可以簡單地使用,

print_r($society); 

P.S.如果你正在做這個AJAX調用,那麼使用這個json_encode函數更好。您可以在JavaScript代碼中使用JSON.parse()方法來解析接收到的響應。