PHP 结果到 JSON 对象


php result to json object

我有一个名为"updates"的数据库表,其中包含分别类型为"int"和"text"的字段"id"和"post"。现在我正在检索所有帖子,如下所示:

$result = mysqli_query($con,"SELECT post FROM updates");
while($row=mysqli_fetch_row($result)){
$postsarray[] = $row;
}

现在我想将此数组转换为 JSON 数组,如下所示:

{
    "posts":[{
            "post1",
            "post2",
            ..
            }]
}

我尝试了很多方法,但无法得到。谁能帮我做到这一点?

$result = mysqli_query($con,"SELECT post FROM updates");
while($row=mysqli_fetch_row($result)){
    $postsarray[] = $row[0];
}
$arr = array();
$arr['posts'] = $postsarray;
$json = json_encode($arr);

mysqli_fetch_row本身返回一个数组(行),因此在添加到$postsarray时必须获取第一个元素。

PHP json_encode 函数将传递给它的数据转换为 JSON 字符串,然后可以输出到 JavaScript 变量。我们在此页面上演示了单级数组。其他页面演示了如何使用具有多维数组和标量值的json_encode

PHP json_encode 函数返回一个字符串,其中包含传递给它的值的 JSON 等效项,正如我们在这里使用数字索引数组演示的那样:

<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>