【问题标题】:How can I convert json into the right format using PDO::FETCH_UNIQUE?如何使用 PDO::FETCH_UNIQUE 将 json 转换为正确的格式?
【发布时间】:2017-07-10 12:02:44
【问题描述】:

我通过 pdo 从 mySQL 数据库获取数据:

$people = $db->query('SELECT * FROM people ORDER BY id ASC;')->fetchAll(PDO::FETCH_UNIQUE);

数组people 如下所示:

array(84) {
  [40]=>
  array(12) {
    ["name"]=>string(5) "Tiger Nixon"
    [0]=> string(5) "Tiger Nixon"
    ["positon"]=> string(7) "System Architect"
    [1]=> string(7) "System Architect"
    ["salary"]=> string(10) "$320,800"
    [2]=> string(10) "$320,800"
    ["start_date"]=> string(11) "2011/04/25"
    [3]=> string(11) "2011/04/25"
    ["office"]=> string(5) "Edinburgh"
    [4]=> string(5) "Edinburgh"
    ["extn"]=> string(5) "5421"
    [5]=> string(5) "5421"

  }
  [41]=>
   array(12) {
    ["name"]=> string(5) "Garrett Winters"
    [0]=> string(5) "Garrett Winters"
    ["positon"]=> string(7) "Accountant"
    [1]=> string(7) "Accountant"
    ["salary"]=> string(10) "$170,750"
    [2]=> string(10) "$170,750"
    ["start_date"]=> string(11) "2011/07/25"
    [3]=> string(11) "2011/07/25"
    ["office"]=> string(5) "Tokyo"
    [4]=> string(5) "Tokyo"
    ["extn"]=> string(5) "8422"
    [5]=> string(5) "8422"
  }
...

如果我现在通过 echo json_encode($people); 将其转换为 json

结果是:

{"40":{
    "name":"Tiger Nixon",
    "0":"Tiger Nixon",
    "position":"System Architect",
    "1":"System Architect",
    "salary":"$320,800",
    "2":"$320,800",
    "start_date":"2011/04/25",
    "3":"2011/04/25",
    "office":"Edinburgh",
    "4":"Edinburgh",
    "extn":"5421",
    "5":"5421",
   },
...

但这不是我需要的格式。其实我需要这种格式:

[
  {
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$320,800",
    "start_date": "2011/04/25",
    "office": "Edinburgh",
    "extn": "5421"
  },
  {
    "name": "Garrett Winters",
    "position": "Accountant",
    "salary": "$170,750",
    "start_date": "2011/07/25",
    "office": "Tokyo",
    "extn": "8422"
  },
...
]

【问题讨论】:

    标签: php mysql json pdo


    【解决方案1】:

    那么你应该告诉fetchAll()你想要返回一个 assoc 数组,而不是 assoc 数组和数值数组。

    ->fetchAll(PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC)
    

    【讨论】:

    • 太棒了!但是之前还有一个号码:{"40":{ "name": "Tiger Nixon", "position": "System Architect", "salary": "$320,800", "start_date": "2011/04/25", "office": "Edinburgh", "extn": "5421" }
    • 我认为最好只使用PDO::FETCH_ASSOC
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多