dongmou5628 2015-02-09 03:20
浏览 21
已采纳

将数组添加到MySQL Fetch

I'm fetching results from my database (fetchAll), and later encoding it into json.

However, I want to add additional values to it, but I have no idea how to achieve that.

I tried doing this is:

while ($posts = $database->fetchAll()) {
    $posts['additional'] = 'test';
}

But it wasn't working.

The result I'm after is changing the results from this:

[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"}, 
    {"firstName":"Peter", "lastName":"Jones"}
]

to

[
    {"firstName":"John", "lastName":"Doe", "additional":"test"}, 
    {"firstName":"Anna", "lastName":"Smith", "additional":"test"}, 
    {"firstName":"Peter", "lastName":"Jones", "additional":"test"}
]

What should I do? Thanks!

  • 写回答

1条回答 默认 最新

  • douwo1517 2015-02-09 03:24
    关注

    Don't use fetchAll and while together.

    Then:

    $posts = array();
    while ($post = $database->fetch()) {
        $post['additional'] = 'test';
        $posts[] = $post;
    }
    

    Or:

    $posts = $database->fetchAll();
    foreach ($posts as &$post) {
      $post['additional'] = 'test';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程