PHP mysql结果json_encode返回键和索引号

时间:2012-10-22 15:01:09

标签: php json

为什么JSON输出同时显示索引号和关联列名?

我只需要列名,例如“UID”

PHP代码

$res = $statement->fetchAll();
$records = array('Record'=>$posts);
echo json_encode($records);

JSON OUTPUT

{
  "Record":[
    {
      "UID":"1001",
      "0":"1001",
      "NAME":"Robot2",
      "1":"Robot2",
      "EMAIL":"robot2@test.com",
      "2":"robot2@test.com",
      "GENDER":"f",
      "3":"f"
    },
    {
      "UID":"1030",
      "0":"1030",
      "NAME":"Anna",
      "1":"Anna",
      "EMAIL":"Anna@msn.com",
      "2":"Anna@msn.com",
      "GENDER":"f",
      "3":"f"
    }
  ]
}

由于

2 个答案:

答案 0 :(得分:4)

默认提取样式为PDO::FETCH_BOTH,您需要将其设置为PDO::FETCH_ASSOC

$res = $statement->fetchAll(PDO::FETCH_ASSOC);

或者您可以通过以下方式设置默认 DEFAULT_FETCH_MODE

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

然后你可以$res = $statement->fetchAll();

答案 1 :(得分:4)

请参阅文档以获得解释:

http://php.net/manual/en/pdostatement.fetchall.php

为了只获取关联项,您应该将PDO::FETCH_ASSOC传递给fetchAll。