sql PDO fetchall重复对象键?

时间:2014-09-29 06:11:21

标签: php sql pdo

我使用PDO方法在fetchAll()中发现了问题。

执行显示对象数组的结果时很好,但每个对象都有重复键,例如:

$catid = intval( $api->param['catid'] );

      $json   = array();
      $prepar = "SELECT * FROM " . DB_PREFIX . "cat_sub WHERE `catid` = :catid ORDER BY `orderid` asc";

      try{

               $q = $api->pdo->prepare($prepar);

               $q->bindparam(":catid" , $catid , PDO::PARAM_INT);

               $q->execute();

               $json = $q->fetchAll();

      }catch( PDOException $e ){

           $api->showError = $e->getMessage();

      }

      echo json_encode($json);
      exit();

每个对象的输出是

{
"subcatid":"6",
"0":"6",
"title":"coool ",
"1":"coool ",
"catid":"2",
"2":"2",
"orderid":"1",
"3":"1"
},

它应该是

{
"subcatid":"6",
"title":"coool ",
"catid":"2",
"orderid":"1",
},

如何在没有循环或foreach的情况下执行此操作的任何建议:)

2 个答案:

答案 0 :(得分:15)

您必须指定fetching mode

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

答案 1 :(得分:3)

请指定提取模式

更改

$json = $q->fetchAll(); 

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