使用循环在 PHP 中生成 JSON 数组


Generating an array of JSON in PHP using a loop

已经

看了一段时间了,它看起来很简单,但由于某种原因我无法掌握它。

我目前的代码输出这个:

{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"}
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}

但我需要的是这个:

[{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"},
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}]

有人可以指出我正确的方向吗?我对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 = array();
while(mysqli_stmt_fetch($statement)){
    $society[] = array(
        'society_id'  = $society_id,
        'name'        = $name,
        'email'       = $email,
        'description' = $description
    );
}
echo json_encode($society);

对于所需的 json 格式,您需要使用多维数组。并且无需在while()循环中使用json_encode()

示例

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