【问题标题】:sql PDO fetchall duplicate object keys?sql PDO fetchall 重复的对象键?
【发布时间】:2014-11-23 11:15:04
【问题描述】:

我在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 的情况下执行此操作的任何建议 :)

【问题讨论】:

    标签: php sql pdo


    【解决方案1】:

    你必须指定fetching mode

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

    【讨论】:

      【解决方案2】:

      请指定获取方式

      改变

      $json = $q->fetchAll(); 
      

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

      【讨论】:

      • 你的回答和@Justinas有什么区别?
      • @RamSharma mine 带有指向所有可用获取模式的文档的链接。
      • 我刚刚指定了错误。就这样。 :) 但是@Justinas 在我之前发布了它。 :)
      • 我觉得两个答案都是一样的,而是更好地重复相同的答案你应该喜欢或投票@Justinas的答案
      • 其实我在回答的时候没看到:)
      猜你喜欢
      • 1970-01-01
      • 2014-05-01
      • 2014-02-05
      • 2017-08-16
      • 1970-01-01
      • 2013-05-01
      • 2020-05-04
      • 1970-01-01
      • 2011-11-19
      相关资源
      最近更新 更多