【问题标题】:How to format a Mysql/php array for json?如何为 json 格式化 Mysql/php 数组?
【发布时间】:2011-05-05 18:57:23
【问题描述】:

之前问过这个问题,但我已将问题缩小到这段代码。这是我的代码,当我运行它时,它只是说“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);

【问题讨论】:

标签: php mysql arrays json


【解决方案1】:

首先,您将 echo 放在循环之外,它只回显最后一项而不是每个人,并且您不检查您的查询是否有错误。

这样就足够了:

$getmsg = "SELECT * FROM user WHERE account_id = $id";      
$result = @mysqli_query($dbc, $getmsg) or die("Error: " . mysql_error());
$result = mysql_fetch_assoc($result);
echo json_encode($result);

它将结果放在一个 assoc 数组中,然后将整个数组转换为 json 并打印出来。

【讨论】:

  • 与作者的问题无关,但使用@是一种不好的风格,以及输出mysql_error()并将MySQLi(mysqli_query())与MySQL(mysql_error())混合。
【解决方案2】:

你可能遇到的问题是在你的赋值语句中:

$arrResults = array($row['user_username']);

您应该将其更改为以下内容:

$arrResults[] = $row['user_username'];

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 2017-11-27
    • 2023-04-04
    • 1970-01-01
    • 2013-02-02
    • 2021-12-18
    • 1970-01-01
    • 2015-01-04
    相关资源
    最近更新 更多