1

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!

2
  • What is your question? Commented Feb 9, 2015 at 3:22
  • I want to add additional data to the currently fetched results (in array). Commented Feb 9, 2015 at 3:23

1 Answer 1

4

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';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Works fine your way. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.