0

One of my PDO statements returns an array. For JSON encoding I want to cast this array to an Object and append it to another array.

     while($row = $sth->fetch()){
            foreach($row as $key=>$value){ 
                    $r = (object) $row;
                    $recordArray[] = $r;
            }
    }

    $json->record = $recordArray;
    echo json_encode($json);

$recordArray seems to stay empty but it doesn't if I write $recordArray[] = "test" in the loop. So there must be something wrong with my Object $r but I can't spot the mistake. Any help is appreciated.

0

3 Answers 3

2

Here is an easier way

echo json_encode(array('record'=>$sth->fetchAll(PDO::FETCH_OBJ)));
Sign up to request clarification or add additional context in comments.

4 Comments

It doesn't work in my case. If I do a var_dump($sth->fetchAll(PDO::FETCH_OBJ));I get an array containing 194 objects (stdClass). But if I do the json_encode with the content of the var_dump I get a blank page.
I just tested this and it woks fine, are you outputting anything else to the page? try right click, view source, you should see the json string
Still can't spot the error. Guess there must be something wrong with my server. Thanks a lot for the shorter statement anyways.
try adding error_reporting(E_ALL); ini_set("display_errors", 1); at the top of your php script and see if you're getting any errors
0

Your foreach is wrong: in body you use object on which you iterate. May be you mean this?

$records = [];
while($row = $sth->fetch()) {
    $current = [];
    foreach($row as $key => $value) {
        $current[$key] = $value;
    }
    $records[] = $current;
}

Comments

0

If I understood, you want to loop over $row and add every object within $row to $recordArray.

Then you should do this:

while($row = $sth->fetch()){
    foreach($row as $value){ 
        $recordArray[] = $value;
    }
}

Comments

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.