php json_encode 对相同的数据进行两次编码

标签 php json

<分区>

我正在从数据库中获取一些数据并将其编码为 json:

$json = "";
if($result = $dbc->query($query)) {
    $num = $result->num_rows;
    for($i = 0; $i < $num; $i++) {
        $row = $result->fetch_array();
        $json .= json_encode($row);
        if($i != ($num-1)) {
        $json .= ',';
        }
    }
}

但不是以以下格式获取 json 字符串:

{"name:"joe", "age":"22", "etc":"etc"}

我得到的每个值都是重复的,因为它给我的元素名称是关联数组和非关联数组的索引。所以我得到:

{"0":"joe", "name":"joe", "1":"22", "age":"22", "3":"etc", "etc":"etc"}

虽然我仍然可以使用 json.它仍然是我想要的大小的两倍,因此效率不高。无论如何我可以获得 json_encode 方法来给我关联数组 inices 作为 json 标签? (毫无疑问,用错误的词来描述这些东西)

非常感谢

最佳答案

这是因为您正在使用 fetch_array() (强调我的):

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

改用fetch_assoc()

关于php json_encode 对相同的数据进行两次编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4663030/

相关文章:

php - “提交评论”重定向到另一个页面

php - 如何从 mp4 文件生成图像?

php 邮件附件

java - 解析数据时出错 org.json.JSONException : Value &lt;! -- java.lang.String 类型无法转换为 JSONObject

python - 如何使用 python -m json.tool 包含\n

json - Golang将网址 slice 转换为JSON网站树

php - 尝试使用表单将信息上载到数据库时,MySQL语法错误

php - 如何从 APC 缓存中排除 .php 文件?

json - Play Framework - 向 JSON 对象添加字段

java - 在 Java 中使用 Freebase API