将Mysql结果集转换为JSON会两次打印相同的字段

时间:2016-03-16 19:53:50

标签: php mysql json

这是php:

{
0: "Source1",
1: "36.11",
2: "19.39",
3: "2016-03-16 19:24:28",
source: "Source1",
temp: "36.11",
mois: "19.39",
timestamp: "2016-03-16 19:24:28"
}

然而,当我运行这个时,我得到的数据如下:

SELECT      sourceName as source,
            tempValue as temp,
            moisValue as mois,
            creation_time as 'timestamp'

FROM        Reading r
ORDER BY    creation_time;

MySQL很简单:

+--------------------------------------------------------------------------+
|    day    | 9-10    | 10-11  | 11-12    | 12-1  | 1-2    |  2-3   |  3-4 |
|---------------------------------------------------------------------------
| Monday    | DA6210  | DA6220  | DA6010  |       | DA6020 |        |      |
| Tuesday   | DA6210  | DA6010  | DA6220  |       | DA6020 |        |      |
| Wednesday | IA6010  | DA6220  |         |       | DA6020 |        |      |
| Thursday  | IA6010  |         | DA6210  |       | GC6210 |        |      |
| Friday    | IA6010  |         | DA6010  |       | GC6210 |        |      |
| Saturday  | DA6210  |         |         |       |        |        |      |
+--------------------------------------------------------------------------+

为什么要添加额外的字段?查询是否运行了两次?

2 个答案:

答案 0 :(得分:3)

fetchAll第一个参数设为PDO::FETCH_ASSOCPDO::FETCH_NUM。默认情况下,它设置为PDO::FETCH_BOTH,为您提供此输出。

$result = $sql->fetchAll(PDO::FETCH_ASSOC);

More info关于FETCH - 参数

答案 1 :(得分:1)

public array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
  

PDO :: FETCH_BOTH(默认值):返回由两列索引的数组   结果集中返回的名称和0索引列号

将PDO :: FETCH_ASSOC用于此声明:

$stmt->fetchAll(PDO::FETCH_ASSOC);

或改变全球行为:

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);