php json_encode 有 2 个键用于同一对象
php json_encode has 2 keys for same object
我正在使用 jQuery ajax 从 php 页面获取 json 对象。
在php这边我用的是
while ($row = mysql_fetch_array($result)) {
array_push($retval, $row);
}
然后
echo json_encode($retval);
到return吧。
我在客户端从 jQuery ajax 获得一个 JSON 调用作为一个数组,每个对象中有两个键用于相同的值。一个键是索引位置,另一个是名称。
例如:数组中的每个对象如下所示:
0: "1234"
1: "2014-11-01"
hc_month: "2014-11-01"
hc_wi_fi_unique: "1234"
关于我为什么会得到这样的结果的任何指示? (JSON_FORCE_OBJECT是用来解决这类问题的吗)
PS:我无法控制在 mysql 上使用 mysqli 或 PDO。仅供参考。
不是 json_encode
问题而是 mysql_fetch_array
:
http://php.net/manual/en/function.mysql-fetch-array.php
The type of returned array depends on how result_type is defined. By
using MYSQL_BOTH (default), you'll get an array with both associative
and number indices. Using MYSQL_ASSOC, you only get associative
indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get
number indices (as mysql_fetch_row() works).
所以 MYSQL_ASSOC
或使用 mysql_fetch_assoc
,尽管我添加了强制性的:关闭 MySQL 扩展并使用 MySQLI 或 PDO.
我正在使用 jQuery ajax 从 php 页面获取 json 对象。
在php这边我用的是
while ($row = mysql_fetch_array($result)) {
array_push($retval, $row);
}
然后
echo json_encode($retval);
到return吧。
我在客户端从 jQuery ajax 获得一个 JSON 调用作为一个数组,每个对象中有两个键用于相同的值。一个键是索引位置,另一个是名称。 例如:数组中的每个对象如下所示:
0: "1234"
1: "2014-11-01"
hc_month: "2014-11-01"
hc_wi_fi_unique: "1234"
关于我为什么会得到这样的结果的任何指示? (JSON_FORCE_OBJECT是用来解决这类问题的吗)
PS:我无法控制在 mysql 上使用 mysqli 或 PDO。仅供参考。
不是 json_encode
问题而是 mysql_fetch_array
:
http://php.net/manual/en/function.mysql-fetch-array.php
The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
所以 MYSQL_ASSOC
或使用 mysql_fetch_assoc
,尽管我添加了强制性的:关闭 MySQL 扩展并使用 MySQLI 或 PDO.