如何将 Mysql/php 数组格式化为 json?
之前问过这个问题,但我已将问题范围缩小到这段代码。这是我的代码,当我运行它时,它只是说“null”..
$getmsg = "SELECT * FROM user WHERE account_id = $id";
$showmsg = @mysqli_query ($dbc, $getmsg);
while ($row = mysqli_fetch_array($showmsg, MYSQLI_ASSOC)) {
$arrResults = array($row['user_username']);
} // END WHILE
// Print them out, one per line
echo json_encode($arrResults);
Asked this before, but I've narrowed down the issue to this bit of code. Here's my code, when I run it, it just says "null"..
$getmsg = "SELECT * FROM user WHERE account_id = $id";
$showmsg = @mysqli_query ($dbc, $getmsg);
while ($row = mysqli_fetch_array($showmsg, MYSQLI_ASSOC)) {
$arrResults = array($row['user_username']);
} // END WHILE
// Print them out, one per line
echo json_encode($arrResults);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您已将 echo 放在循环之外,该循环仅回显最后一项而不是所有人,并且您不会检查查询是否有错误。
相反,这就足够了:
它将结果放入一个 assoc 数组中,然后将整个数组转换为 json 并打印它。
First of all you have put the echo outside the loop which just echoes the last item instead of everyone and you don't check if there is a error with your query.
Instead this would be sufficient:
It puts the result in one assoc array and then converts the whole array to json and prints it.
您可能遇到的问题是在您的赋值语句中:
$arrResults = array($row['user_username']);
您应该将其更改为以下内容:
$arrResults[] = $row['user_username'];
The problem you are likely having is in your assignment statement:
$arrResults = array($row['user_username']);
You should change it to the following:
$arrResults[] = $row['user_username'];