2016-03-07 98 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()方法来解析接收到的响应。