3

我正在查询一个返回字段(message_type 和百分比)的表。我使用 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]
]

我也尝试手动对其进行编码,但无法获得所需的结果。

4

1 回答 1

8

PHPjson_encode()使用一定的魔法来确定给定的向量是编码为 JSON 对象还是数组,但简单的规则是:如果数组有连续的、零索引的数字键,它将被编码为数组. 任何其他向量(对象或关联数组)都将被编码为对象。

因为您正在使用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;
}
于 2013-04-09T23:38:23.990 回答