我想在 php 中实现这个输出。
[
{
"id": 1388534400000,
"author": "Pete Hunt",
"text": "Hey there!"
},
{
"id": 1420070400000,
"author": "Paul O’Shannessy",
"text": "React is *great*!"
}
]
我在下面的后端有一个 while 循环
。
$pull = "SELECT * FROM mydb";
$result = $con->query($pull);
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json['id'] = $row['id'];
$json['author'] = $row['author'];
$json['text'] = $row['text'];
}
echo json_encode($json);
它只返回数据库中的最后一行,我想把它们全部显示出来。
谢谢。
最佳答案
如果您的$row
仅包含数据库中的这三个字段,则使用下面的代码,否则@govindkr13 回答
$pull = "SELECT * FROM mydb";
$result = $con->query($pull);
$json = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$json[] = $row;
}
echo json_encode($json);
关于php - 如何在php中这样输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35916394/