在 PHP 中使用 while 循环创建一个 JSONArray


Create a JSONArray using a while loop in PHP

我将把数组发送到java以填充ListView,如何获取以下代码来输出数组?

<?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":"Test@email1","description":"TestDes1"}
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}
{"society_id":3,"name":"TestName3","email":"Test@email3","description":"TestDes3"}

在发布此内容之前,我已经查看了互联网,但感到非常困惑!提前感谢任何人。

如果你

想要一个数组,你就走得太远了,也错过了一步。您正在 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;
}

现在,您可以对大型$society数组执行任何需要的操作。

如果您只是想要数组形式的输出,那么为什么要将其编码为 JSON? 您可以简单地使用,

print_r($society);

附言:如果您正在为 AJAX 调用执行此操作,那么使用此json_encode函数会更好。你可以在 JavaScript 代码中使用 JSON.parse() 方法来解析收到的响应。