【问题标题】:PHP JSON output with mysql for tag-it带有 mysql 的 PHP JSON 输出用于 tag-it
【发布时间】:2012-05-08 22:22:03
【问题描述】:

我正在尝试让 tag-it jquery 插件与 json 字符串一起使用。 目前我正在像这样从数据库中获取我的值:

$query = sprintf(
            'SELECT
                t.tag
            FROM
                tags AS t
            ');

    $row_set= array();

    if($result = mysqli_query($db, $query))
    {
        // fetch data
        while ($row = mysqli_fetch_assoc($result))
        {
            $row_set[] = $row;
        }

        // set the output
        echo json_encode($row_set);
    }

在 AJAX 中调用时会给出以下输出:

[{"tag":"test"},{"tag":"tests"}]

但我必须以以下格式输出 JSON 字符串:

["android-intent","animate","architecture","artificial-intelligence","attributes"]

我怎样才能做到这一点?

【问题讨论】:

    标签: php mysql ajax json tag-it


    【解决方案1】:

    当您使用row_set[] = $row; 时,$row 很可能看起来像这样$row['tag'] = 'test,这就是您使用 JSON 对象格式的原因;

    试试

      $row_set[] = $row['tag']; 
    

    确保您还将 seound 参数设置为 true 以使 JSON 始终返回数组

       json_encode($row_set,true);
    

    这会将它作为数组而不是对象返回

    【讨论】:

    • 这给了我正确的输出,但是标签 - 它在自动完成中给出了所有字符作为建议,它给出了 [" 测试作为单独的'标签'......编辑:没关系!忘记了数据类型: "json",
    【解决方案2】:

    这应该可以解决它,通过在箭头中添加字符串而不是在数组中添加数组。

    $row_set[] = $row[0]; or $row_set[] = $row['tag'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多