将数组添加到MySQL Fetch

时间:2015-02-09 03:20:42

标签: php mysql arrays json fetch

我从我的数据库(fetchAll)中获取结果,然后将其编码为json。

但是,我想为它添加其他值,但我不知道如何实现它。

我试过这样做:

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

但它没有用。

我所追求的结果是改变了结果:

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

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

我该怎么办?谢谢!

1 个答案:

答案 0 :(得分:4)

请勿同时使用fetchAllwhile

然后:

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

或者:

$posts = $database->fetchAll();
foreach ($posts as &$post) {
  $post['additional'] = 'test';
}