我从我的数据库(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"}
]
我该怎么办?谢谢!
答案 0 :(得分:4)
请勿同时使用fetchAll
和while
。
然后:
$posts = array();
while ($post = $database->fetch()) {
$post['additional'] = 'test';
$posts[] = $post;
}
或者:
$posts = $database->fetchAll();
foreach ($posts as &$post) {
$post['additional'] = 'test';
}