我正在查询一个返回字段的表(message_type& percentage)。我使用PHP对json数据进行编码,如下所示
$json = array();
while ($row = odbc_fetch_array($rs)) {
$json[][] = $row;
}
echo json_encode($json);输出:
[ [ { "message_type" : "bullying",
"percentage" : "60"
} ],
[ { "message_type" : "cheating",
"percentage" : " 14"
} ],
[ { "message_type" : "Stress",
"percentage" : "16"
} ],
[ { "message_type" : "Gang",
"percentage" : "7"
} ]
]正如您所看到的,json_encode函数添加了大括号、引号和对象键名称。
我想要的是只将json解析为二维数组,以下是所需的输出:
[
["bullying", 60],
["harrassment", 9],
["cheating", 14],
["Stress", 16],
["Gang", 7]
]我也尝试过手动编码,但是我不能得到我需要的结果。
发布于 2013-04-10 07:38:24
PHP使用一定的魔力来确定给定的向量是编码为json_encode()对象还是数组,但简单的规则是:如果数组具有连续的、零索引的数字键,则将其编码为数组。任何其他向量(对象或关联数组)将被编码为对象。
因为您使用的是odbc_fetch_array(),所以结果行以关联数组的形式返回,键是列名。要得到你想要的结果,你有3个选择:
通过array_values()传递结果行
$json[] = array_values($row);手动构造单个数组:
$json[] = array($row['message_type'], $row['percentage']);或者最好的选择是使用odbc_fetch_row(),它将直接返回索引数组:
while ($row = odbc_fetch_row($rs)) {
$json[] = $row;
}https://stackoverflow.com/questions/15914282
复制相似问题